Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

jquery - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...