Search code examples
javascriptjquerycssxmloptgroup

Is it possible to make an option of a select dropdown appear as optgroup via css


I am actually populating options from xml for my dropdown and Now adding an optgroup to select is a challenge. Can I add them manually and change the behaviour via css


Solution

  • You can add options and optgroups to the select box manually after the fact with jQuery. Assuming your HTML is already available, you could do something like this:

    $("select").append("<optgroup label='Example'><option>Test1 </option> <option>Test 2</option></optgroup>")
    

    If you already have options in the select element, then it would just be a matter of finding all of those options that you would like to group up (via a class name or value attribute, perhaps), then pushing them into a newly create optgroup, then appending the optgroup into the select. Example:

    var optionsToGroup = $("option.groupthis");
    var optGroup = $("<optgroup></optgroup>").append(optionsToGroup);
    $('select').append(optGroup);
    

    Edit: Based on the Fiddle you've provided, I modified your jQuery code to build the optgroup before the options. This isn't the most efficient way, but it should get you started based on what you've provided. See http://jsfiddle.net/xUJZj

    var title = $(this).find('title').text();
    var optgrouping = "<optgroup label='"+title+"'></optgroup>";
    var options = [];
    $(this).find('value').each(function(){
              var value = $(this).text();
              options.push("<option class='ddindent' value='"+ value +"'>"+value+"</option>");
     });
      var grouping = $(optgroupting).html(options.join(''));
      select.append(grouping);
    

    Edit 2: I've modified the JSFiddle to use an actual XML doc (similar to what you provided). See it here: http://jsfiddle.net/xUJZj/13/ Or, the relevant modified code is here below:

    function createSelect(xml)
    {
                    var select = $('#mySelect');
                    $(xml).find('menuitem').each(function(){
                        var title = $(this).find('title').text();
                        var optgrouping = "<optgroup label='"+title+"'></optgroup>";
                        var options = [];
                        $(this).find('value').each(function(){
                            var value = $(this).text();
                            options.push("<option class='ddindent' value='"+ value +"'>"+value+"</option>");
                        });
                        var group = $(optgroupting).html(options.join(''));
                        select.append(group);
                    });
                    select.children(":first").text("please make a selection").prop("selected",true);
                }
            });
    }