If I have an option list like the below:
<select name="optionList" id="optionList">
<optgroup label="optgroup1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</optgroup>
<optgroup label="optgroup2">
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</optgroup>
</select>
I know I can access the selectedIndex using:
document.getElementById('optionList').selectedIndex;
If I use the above though the selected index of 5 will be 4, 6 will be 5, 7 will be 6, etc
How can I tell where a selected item in an optgroup is?
In summary I'd like to be able to query something and get back its position in the optgroup so that 5 would return 0, 6 would return 1 etc...
This is a slightly complex task, because there is no native way to do it. I'm going to answer according to current browser standards: it's possible to do it in older browsers, but it is more work.
var select = document.getElementById('optionList'), // the <select> element
selectedIndex = select.selectedIndex, // 0-based index of which element in the <select> is selected
selectedElement = select.options[selectedIndex], // DOM element selected
optGroup = selectedElement.parentNode, // <optgroup> element
optGroupOptions = optGroup.children, // <option> elements in the <optgroup>
positionInOptGroup = Array.prototype.indexOf.call(optGroupOptions, selectedElement); // the selected <option>'s position in the <optgroup>
(jsFiddle)
Note that this will not work if the browser does not support Element#children
(i.e. IE <9). You will have to filter the childNodes
collection into an array at test against that. Similarly, it requires Array#indexOf
, which also didn't exist in IE <9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With