How to get the Index of select->option tag

2019-01-17 21:06发布

<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

8条回答
成全新的幸福
2楼-- · 2019-01-17 21:38

This will do it:

   $("#sel").attr("selectedIndex")
查看更多
孤傲高冷的网名
3楼-- · 2019-01-17 21:40

You can actually do it without jQuery: var sel = document.getElementById( 'sel' ); var index = sel.selectedIndex;

查看更多
4楼-- · 2019-01-17 21:40

The title doesn't quite match the question...

How to get the Index of select->option tag

option.index // javascript

$(option).prop('index') // jquery

index of selected select->option tag:

document.getElementById('sel').selectedIndex // javascript
查看更多
对你真心纯属浪费
5楼-- · 2019-01-17 21:46

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;
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-17 21:51
$("#sel").attr("selectedIndex")

or

$("#sel")[0] //to get the DOM element
$("#sel")[0].selectedIndex
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-17 21:53

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/

查看更多
登录 后发表回答