Homer_J
Homer_J

Reputation: 3323

How can I add OPTGROUP to select statement?

I'm building a dropdown option via jQuery using the following:

var myOptions = {
    var1 : 'Road',
    var2 : 'Rail'
};

var mySelect = $('#q54');
    $.each(myOptions, function(val, text) {
        mySelect.append(
            $('<option></option>').val(text).html(text)
    );
});

Building the dropdown, no problem - I'm then trying to append optgroupoptions - I've tried adding in the following code to wrap the optgroup around the option but no joy.

var i = 1; // Addition
$.each(myOptions, function(val, text) {
    if(i == 1){
        $("#q54").append('<optgroup class="optgroups" label="Team">');
    }
    mySelect.append(
        $('<option></option>').val(text).html(text)
    );
    if(i == 2){
        $("#q54").append('</optgroup>');
    }
});

The HTML output of the above is:

<optgroup class="optgroups" label="Team"></optgroup>
<option value="Road">Road</option>

The output should be:

<optgroup class="optgroups" label="Team">
    <option value="Road">Road</option>
</optgroup>

Any advice welcomed.

Upvotes: 0

Views: 2505

Answers (1)

rrk
rrk

Reputation: 15846

Considering jQuery append() like the html string is the issue you are facing here.

var myOptions = {
    var1 : 'Road',
    var2 : 'Rail'
};    
var i = 1; // Addition
var $group = $('<optgroup class="optgroups" label="Team">');
$("#q54").append($group);
$.each(myOptions, function(val, text) {
    $group.append($('<option></option>').val(text).html(text));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="q54"></select>

Another solution is to use wrapAll() like Pointy suggested.

var myOptions = {
    var1 : 'Road',
    var2 : 'Rail'
};    
var i = 1; // Addition
$.each(myOptions, function(val, text) {
    $("#q54").append($('<option></option>').val(text).html(text));
});
$("#q54").children().wrapAll('<optgroup class="optgroups" label="Team">');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="q54"></select>

Upvotes: 4

Related Questions