Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Index of select->option tag

<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

like image 933
Vov4ik Avatar asked Nov 29 '09 23:11

Vov4ik


People also ask

How do you find the value of an option tag?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).

What is the selected index?

selectedIndex is a long that reflects the index of the first or last selected <option> element, depending on the value of multiple . The value -1 indicates that no element is selected.


Video Answer


1 Answers

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.

like image 76
Chris Moschini Avatar answered Oct 14 '22 07:10

Chris Moschini