开发者

how to get the selected index of a drop down

开发者 https://www.devze.com 2023-01-14 10:21 出处:网络
I have a normal dropdown which I want to get the currently selected index and put that in a variable. Jquery or javascript. Jquery perfered.

I have a normal dropdown which I want to get the currently selected index and put that in a variable. Jquery or javascript. Jquery perfered.

<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test  xxxx1234</option>
<option value="1962">test2  xxxx3456</op开发者_StackOverflowtion>
</select> 


$("select[name='CCards'] option:selected") should do the trick

See jQuery documentation for more detail: http://api.jquery.com/selected-selector/

UPDATE: if you need the index of the selected option, you need to use the .index() jquery method:

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


This will get the index of the selected option on change:

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


If you are actually looking for the index number (and not the value) of the selected option then it would be

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

or using jQuery

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


the actual index is available as a property of the select element.

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

you can use the index to get to the selection option, where you can pull the text and value.

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


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


You can also use :checked for <select> elements

e.g.,

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

You don't even have to get the index and then reference the element by its sibling index.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号