Add optgroup dynamically to an existing select

119 Views Asked by At

I have an existing select with 5 options and a default blank value. I want to add an optgroup to the first 3 values and another optgroup to the last two options.

<select id="cityDropdown">
    <option selected="selected" value="" label=" "> </option>
    <option value="1000">Tokyo</option>
    <option value="1001">Kyoto</option>
    <option value="1002">Osaka</option>
    <option value="1003">Incheon</option>
    <option value="1004">Busan</option>
</select>

I want my select to look like this

<select id="cityDropdown">
    <optgroup label="Japan">
        <option value="1000">Tokyo</option>
        <option value="1001">Kyoto</option>
        <option value="1002">Osaka</option>
    </optgroup>
    <optgroup label="SoKorea">
        <option value="1003">Incheon</option>
        <option value="1004">Busan</option>
    </optgroup>
</select>

Below is my existing code which no longer works since the values are no longer even.

$(document).ready(function() {
    var select = $('#cityDropdown');
    var opt1, opt2;
    $('option', select).each(function(i) {
        if (i % 2 === 0) {
            opt1 = $(this);
        } else {
            opt2 = $(this);
            var optgroup = $('<optgroup/>');
            optgroup.attr('label', label);
            opt2.add(opt1).wrapAll(optgroup);
        }

    });
});
0

There are 0 best solutions below