I thought this would be simple, but is there a way to get the index of a value in a dropdown/combobox without looping through the items?
Asked
Active
Viewed 1,018 times
0
-
Is this an [answer](http://stackoverflow.com/a/1085810/4405465) to your question? – Hasse Björk Nov 14 '15 at 18:53
3 Answers
1
I guess you are talking about select tag and you are trying to get the index of an option by it's value. If so, here is what you need to do:
// Get the select
var select = document.getElementById('mySelect');
// Get the option
var option = select.querySelector('option[value="myValue"]');
// Get the index of that option
var index = Array.prototype.indexOf.call( select.children, option );

metal03326
- 1,213
- 2
- 13
- 15
1
You don't need jQuery for this. You can do it natively with modern Javascript.
var myOption = document.querySelector('option[value="audi"]');
console.log(myOption.index); //returns index = 3
Example here: http://jsfiddle.net/08qzLgbh/
Based on this HTML:
<select>
<option value="volvo">Volvo</option> <!-- index 0 -->
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option> <!-- index 3 -->
</select>

Marc
- 11,403
- 2
- 35
- 45
0
The answer involves jQuery and selectors, and is probably not all that efficient anyway, but it's probably what you want :
var o = $('option[value="something"]','#mycombo');
Simple enough (:

DannyZB
- 523
- 2
- 16
-
1jQuery isn't necessary for this, nor is it tagged in the user's question. – Marc Nov 14 '15 at 19:00