2010-09-02 54 views
35

我有一個正常的下拉,我想獲得當前選定的索引,並把它放在一個變量。 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> 

回答

60

$("select[name='CCards'] option:selected")應該做的伎倆

見jQuery的文檔獲取更多細節:http://api.jquery.com/selected-selector/

UPDATE: 如果你需要選擇的選項的指數,您需要使用.index()的jQuery方法:

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

調用'index()'比單純使用標準DOM'selectedIndex'更加可讀的繁忙工作列表搜索繁忙工作。我會堅持使用純DOM屬性。 – bobince 2010-09-02 15:00:15

+0

@bobince:我也不會用jQuery來解決這個問題,但是因爲OP要求提供jQuery解決方案...... :-) – naivists 2010-09-02 15:02:49

+0

這是最簡單的,正是我所期待的。第二行工作完美,我用它像var indx = $(「select [name ='CCards'] option:selected」)。index(); – user357034 2010-09-02 15:02:59

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

這將得到改變所選擇的選項的索引:

$('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>

+0

不錯,謝謝... – PaulM 2013-05-05 15:18:36

9

實際指標可以作爲選擇元素的屬性。

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

您可以使用索引轉到選擇選項,您可以在其中拉取文本和值。

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

如果你實際上是所選選項尋找索引號(而不是值),那麼它會使用jQuery

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

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

你也可以使用:checked代替<select>元件

例如,

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

您甚至不必獲取索引,然後通過其兄弟索引引用該元素。

相關問題