As I write this, two of the top answers (including the accepted answer) are incorrect despite being pointed out nearly five years ago. attr("selectedIndex")
does nothing, because selectedIndex
is a property on the actual DOM element, not an HTML attribute. You need to use prop
:
$(this).prop('selectedIndex')
Interactive demo comparing this to the incorrect version: http://jsfiddle.net/uvwkD/
Use the standard index function of jquery like in this code example
$("#sel option:selected").index()
You can get the index of the element in this case by checking how many sibling elements the selected element has before it:
$('#sel option:selected').prevAll().length;
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.
$("#sel").attr("selectedIndex")
or
$("#sel")[0] //to get the DOM element
$("#sel")[0].selectedIndex
You can actually do it without jQuery:
var sel = document.getElementById( 'sel' );
var index = sel.selectedIndex;