Question

Below is an example of my markup

<select id = "select_test">
<option>aus - testa1</option>
<option>aus - testa2</option>
<option>aus - testa3</option>
<option>bris - testb1</option>
<option>bris - testb2</option>
<option>bris - testb3</option>
<option>melb - testc1</option>
<option>melb - testc2</option>
<option>melb - testc3</option>
</select>

Using jQuery I am trying to dynamically create optgroups from the everything before the ' - '.

Example of what I would want it to become

<select id = "select_test">
<optgroup label = "aus">
<option>testa1</option>
<option>testa2</option>
<option>testa3</option>
</optgroup>
<optgroup label = "brisb">
<option>testb1</option>
<option>testb2</option>
<option>testb3</option>
</optgroup>
<optgroup label = "melb">
<option>testc1</option>
<option>testc2</option>
<option>testc3</option>
</optgroup>
</select>

Any help would be appreciated!!

Was it helpful?

Solution

You need to loop through each option, splitting the values to find the group name to create. Something like this:

var prevGroup, $group = $();
$('#select_test option').remove().each(function() {
    var $option = $(this),
        values = $option.text().split(' - '),
        group = values[0];

    if (group != prevGroup) {
        $group = $('<optgroup />', { label: group }).appendTo('#select_test');
    }

    $group.append($('<option />', {
        text: values[1],
        value: values[1]
    }));

    prevGroup = group;
});

Example fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top