Skip to content Skip to sidebar Skip to footer

Storing Select Options And Optgroups In A JavaScript Array

I'm making a jQuery plugin that loops through html select

Solution 1:

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


Solution 2:

It's possible, but as an object {} rather than an array [] (which in JavaScript has strictly ordered numeric keys, zero based):

myObj = {
  'group1': ['option 1', 'option 2'],
  'group2': ['option 3', 'option 4']
};

You might create it using something like the following in plain JavaScript.

var myObj = {};
// Get a reference to the <select>
var theSelect = document.getElementById('theSelect');
// And a node list of its <optgroup>
var optgroups = theSelect.getElementsByTagName('optgroup');
// Loop over the <optgroup>
for (var i=0; i<optgroups.length; i++) {
  // And create an object property named with the optgroup label
  myObj[optgroups[i].getAttribute('label')] = [];
  var options = optgroups[i].getElementsByTagName('option');
  // Loop over the <option>s inside it
  for (var j=0; j<options.length; j++) {
    // And stuff them into an array on the new object property:
    myObj[optgroups[i].getAttribute('label')].push(options[j].innerHTML);
  }
}
console.log(JSON.stringify(myObj));​
// {"group1":["option 1","option 2"],"group2":["option 3","option 4"]}

Here's a working fiddle.


Solution 3:

You can store this as an object

myArray = {
    'group1' : ['option 1', 'option 2'],
    'group2' : ['option 3', 'option 4']
};

Here can access the options inside optgroup using ..

myArray.group1[0] // Will give you option 1 
myArray.group2[0] // Will give you option 3 

Post a Comment for "Storing Select Options And Optgroups In A JavaScript Array"