Search code examples
javascriptjqueryselectlistoptgroup

Populating Select List including OptGroup


I'm populating a select list with an array of data. Like this:

$(somedata).each(function() {
    $(document.createElement('option'))
        .attr('value', this.Value)
        .text(this.Text)
        .appendTo(SelectList);
});

How do I append optgroups in the same way? the array of data is a list with the properties Text, Value, OptGroup (boolean) and ordered so the OptGroup comes first followed by it's options. Like this:

[
    ['OptGroup1', 'OptGroup1', true]
    ['Value1', 'Value1', false]
    ['Value2','Value2',false]
    ['OptGroup2', 'OptGroup2', true]
    // ...
]

Solution

  • The answer is pretty straightforward - check if 3rd value is true or false and create the proper element accordingly.

    a few points though:

    • optgroups are appended to the select, while options need to be appended to the last optgroup that you have added. an optgroup is a container of options, and not a title that comes before them.
    • the text on the optgroup is set by the label="" attribute, and not value/text.

    $(function () {
        var somedata = [
            ['OptGroup1', 'OptGroup1', true],
            ['Value1', 'Value1', false],
            ['Value2', 'Value2', false],
            ['OptGroup2', 'OptGroup2', true],
            ['Value3', 'Value3', false],
            ['Value4', 'Value4', false]
        ];
        console.log(somedata);
        var SelectList = $("#SelectList");
        $(somedata).each(function () {
            var $newElem;
            if ($(this)[2] == false) {
                $newElem = $(document.createElement('option')).attr('value', this[1])
                .attr('label', this[0])
                .appendTo(SelectList.find("optgroup").last());
            } else {
                $newElem = $(document.createElement('optgroup')).attr('value', this[1])
                .attr('label', this[0])
                .appendTo(SelectList);;
            }
    
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="SelectList"></select>