0

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?

Voss Grose
  • 185
  • 1
  • 1
  • 7

3 Answers3

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