<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
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With