Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find select option position?

I'm trying to find an option's index.

For example, I would like to get 1 when I run the following fake code

JS:

$("#test[value='USD']").index() ?

HTML:

<select id='test'>
  <option value='CNY'>CNY</option>
  <option value='USD'>USD</option>
</select>

is this possible?

like image 631
Moon Avatar asked Jul 21 '11 08:07

Moon


People also ask

How do I know which option is selected in dropdown?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.


1 Answers

You were very close, you want to use index on the option element, not the select:

var i = $("#test option[value='USD']").index();

Gratuitous live example

Note that this will break if your select contains optgroup elements. If so, you'll want to pass 'option' into index:

var i = $("#test option[value='USD']").index('option');

Live example (I changed the position so it's the 4th element for that example)

like image 53
T.J. Crowder Avatar answered Oct 11 '22 14:10

T.J. Crowder