如何获取下拉菜单的选定索引

42
我有一个普通的下拉菜单, 我想获取当前选中的索引并将其放入一个变量中。 使用 jQuery 或 JavaScript,首选jQuery。
<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test  xxxx1234</option>
<option value="1962">test2  xxxx3456</option>
</select> 
6个回答

65

$("select[name='CCards'] option:selected")应该就可以实现了。

更多细节请参阅jQuery文档:http://api.jquery.com/selected-selector/

更新: 如果您需要选定选项的索引,那么您需要使用.index() jQuery方法:

$("select[name='CCards'] option:selected").index()

5
调用 index() 方法会比使用标准的 DOM 属性 selectedIndex 进行列表搜索耗费更多的工作量,而且并没有增加可读性。在这里,我建议仍然使用普通的 DOM 属性。 - bobince
1
@bobince:我也不会用jQuery来解决这个问题,但既然OP要求使用jQuery解决方案... :-) - naivists
这是最简单的,也正是我在寻找的。第二行代码完美地运行了,我使用它像这样:var indx = $("select[name='CCards'] option:selected").index(); - user357034

26

在更改时,这将获取所选选项的索引:

$('select').change(function(){
    console.log($('option:selected',this).index()); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test  xxxx1234</option>
<option value="1962">test2  xxxx3456</option>
</select>


24

如果你实际上是在寻找所选选项的索引号(而不是值),那么它将是:

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */

或者使用 jQuery

$('select[name="CCards"]')[0].selectedIndex 

15
var sel = document.getElementById('CCards');
alert(sel.selectedIndex);

您可以使用索引获取选项,从而获取文本和值。

var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);

5
<select name="CCards" id="ccards">
    <option value="0">Select Saved Payment Method:</option>
    <option value="1846">test  xxxx1234</option>
    <option value="1962">test2  xxxx3456</option>
</select>

<script type="text/javascript">

    /** Jquery **/
    var selectedValue = $('#ccards').val();

    //** Regular Javascript **/
    var selectedValue2 = document.getElementById('ccards').value;


</script>

2
您还可以在 <select> 元素中使用 :checked

e.g.,

document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')

你甚至不需要获取索引,然后通过其兄弟索引引用该元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接