Alex Rivera | Logout

How to get the Index of select->option tag

Asked 2009-11-29T23:00:56.457
19
<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

Edit
Report

1 Answer

18

Only Bob's second answer is correct:

$("#sel")[0].selectedIndex

Works: http://jsfiddle.net/b9chris/wxeVN/1/

Using .attr() works only if the user (or browser's DOM restore) has not changed the option selected since the page loaded: http://jsfiddle.net/b9chris/wxeVN/

You could implement this as a jQuery extension, and get a little more info in the process:

(function($) {
    $.fn.selectedOption = function() {
        var sel = this[0];
        return sel.options[sel.selectedIndex];
    };
})(jQuery)

$('button').click(function() {
    $('#output').text('selected index: ' + $('select').selectedOption().index);
});

http://jsfiddle.net/b9chris/wxeVN/102/

What's returned by .selectedOption() is the actual option tag, so you can access .index, .value, and .text - a bit more convenient than just the index in typical usage.

answered 2012-07-17T00:31:00.740

Your Answer