Search code examples
javascriptjqueryhtmlselectoptgroup

Storing select options and optgroups in a JavaScript array


I'm making a jQuery plugin that loops through html select <option> tags and outputs them in a different format.
When looping through the options, I'd also like to maintain the relationship between them and <optgroup>s. Being a PHP guy I thought a multidimensional associative array would be the answer. So something like this:

<select>
    <optgroup label="group1">
        <option>option 1</option>
        <option>option 2</option>
    </optgroup>
    <optgroup label="group2">
        <option>option 3</option>
        <option>option 4</option>
    </optgroup>
</select>

...would turn into something like this:

myArray = [
    ['group1'] => ['option 1', 'option 2'],
    ['group2'] => ['option 3', 'option 4']
];

Is this possible in javascript or jQuery?


Solution

  • Some fancy jQuery code, I believe it should work tested it, and it works as expected.

    var o = {};
    
    $('optgroup').each(function() {
        o[this.label] = $(this).find('option').map(function() {
            return $(this).text();
        }).get();
    });
    
    console.log(o);​
    

    Live DEMO