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
?
Some fancy jQuery code, I
believe it should worktested it, and it works as expected.Live DEMO
You can store this as an object
Here can access the options inside optgroup using ..
It's possible, but as an object
{}
rather than an array[]
(which in JavaScript has strictly ordered numeric keys, zero based):You might create it using something like the following in plain JavaScript.
Here's a working fiddle.