Search code examples
javascriptjqueryhtmlselectoptgroup

Dynamic option groups for Select element based on alphabet


I'm generating a select list dynamically from an array of data and I want to add option group based on alphabet.

e.g. data

data = [
  ['bcde','21254'], ['abcd','1234'], ['abcde','23456'], ['bcdef','3232']
];

data.sort(); takes care of ordering based on alphabet and then I go through the data and on each I do something like:

<option value="item[1]">item[0]</option>

However what I want to do is, after getting the items sorted based on alphabet, check the first character of each item and create option group based on that, when character of next item is different create a new option group labelled with the new character

so the output should look like:

<select>
    <optgroup label="A">
        <option value="1234">abcd</option>
        <option value="23456">abcde</option>
    </optgroup>
    <optgroup label="B">
        <option value="21254">bcde</option>
        <option value="3232">bcdef</option>
    </optgroup>
</select>

Can anyone please advice what's the best way to do this, I'm using jquery by the way, cheers.

Edit, this is my current code:

$.when( $.indexedDB("dbname").objectStore('employee').each(function(item){
  employeenames.push([item.value.name,item.value.id]);
}).then(function(){
  employeenames.sort();
  $.each(employeenames, function(index, item){
   employeenames[index] = '<option value="'+item[1]+'">'+item[0]+'</option>';
  });           
 })
).done(function() {
  $("#employeenameBox select").html(employeenames);
});

Solution

  • Try

    data.sort();
    
    var chars = {};
    $.each(data, function (_, item) {
        var char = item[0].charAt(0).toUpperCase();
        if (!chars[char]) {
            chars[char] = $('<optgroup />', {
                label: char
            }).appendTo('select');
        }
    
        $('<option />', {
            text: item[0],
            value: item[0]
        }).appendTo(chars[char]);
    });
    

    Demo: Fiddle

    Update:

    $.when($.indexedDB("dbname").objectStore('employee').each(function (item) {
        employeenames.push([item.value.name, item.value.id]);
    }).then(function () {
        employeenames.sort();
    
        var chars = {};
        $.each(employeenames, function (_, item) {
            var char = item[0].charAt(0).toUpperCase();
            if (!chars[char]) {
                chars[char] = $('<optgroup />', {
                    label: char
                }).appendTo('#employeenameBox select');
            }
    
            $('<option />', {
                text: item[0],
                value: item[0]
            }).appendTo(chars[char]);
        });
    });