Quantcast
Channel: Day Barr's blog
Viewing all articles
Browse latest Browse all 10

Find index of selected option

$
0
0

Given this HTML…

<select><option>Index zero</option><option>Index one</option><option>Index two</option></select><p>Selected option has index: <span id="output">0</span></p>

here is a jQuery code snippet to find the index of the option that has been selected.

$('select').change(function() {
  $('#output').text(
    var $this = $(this);
    $this.children().index( $this.children(':selected') )
  );
}).trigger('change');

Use jQuery's index function to return the index of the item that matches the ':selected' selector within the children of the select element.

Example:


Viewing all articles
Browse latest Browse all 10

Trending Articles