tags:

views:

121

answers:

4
<select id="sel">
<option value="123" selected="selected">text1</option>
<option value="44">text2</option>
<option value="882">text3</option>
...
</select>

How to get the index of selected option with jQuery? May be .index(subject), but all possibilities tested, didn't work...

P.S. Indexes: value="123" => 0, value="44" => 1, ...

Thanx

+1  A: 

You can actually do it without jQuery: var sel = document.getElementById( 'sel' ); var index = sel.selectedIndex;

Jacob Relkin
+3  A: 

This will do it:

   $("#sel").attr("selectedIndex")
Steve Kemp
+1  A: 
$("#sel").attr("selectedIndex")

or

$("#sel")[0] //to get the DOM element
$("#sel")[0].selectedIndex
Bob
+1  A: 

You can get the index of the element in this case by checking how many sibling elements the selected element has before it:

$('#sel option:selected').prevAll().length;
antti_s
This seems like a round about way of getting the selected index, what is the cost of prevAll?
Bob
You are right, checking for the selectedIndex is better in this case. prevAll() however should be faster then fiddling around with the native .index() method here which was the OP's initial solution (unless using jQuery 1.3.3)
antti_s