如何获取下拉列表的选定索引

use*_*034 38 javascript jquery

我有一个正常的下拉列表,我想获得当前选择的索引并将其放入变量中.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> 
Run Code Online (Sandbox Code Playgroud)

nai*_*sts 63

$("select[name='CCards'] option:selected") 应该做的伎俩

有关更多详细信息,请参阅jQuery文档:http://api.jquery.com/selected-selector/

更新:如果需要所选选项的索引,则需要使用.index()jquery方法:

$("select[name='CCards'] option:selected").index()
Run Code Online (Sandbox Code Playgroud)

  • 调用`index()`比使用标准DOM`selectedIndex`更具列表搜索繁忙工作的数量级,并且不再具有可读性.我坚持使用普通的DOM属性. (5认同)

Jam*_*iec 25

这将获得所选选项的索引:

$('select').change(function(){
    console.log($('option:selected',this).index()); 
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


RoT*_*oRa 23

如果您实际上正在查找所选选项的索引号(而不是值),那么它就是

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */
Run Code Online (Sandbox Code Playgroud)

或者使用jQuery

$('select[name="CCards"]')[0].selectedIndex 
Run Code Online (Sandbox Code Playgroud)


lin*_*lnk 10

实际索引可用作select元素的属性.

var sel = document.getElementById('CCards');
alert(sel.selectedIndex);
Run Code Online (Sandbox Code Playgroud)

您可以使用索引来获取选择选项,您可以在其中提取文本和值.

var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 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>
Run Code Online (Sandbox Code Playgroud)