views:

48

answers:

5

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</option>
</select> 
+1  A: 

$("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()
naivists
Calling `index()` is orders of magnitude more list-searching busy-work than just using standard DOM `selectedIndex` and no more readable. I'd stick with the plain DOM property here.
bobince
@bobince: I wouldn't use jQuery to solve this question either, but as the OP asked for a jQuery solution... :-)
naivists
This was the simplest and exactly what I was looking for. The second line works perfect i used it like var indx = $("select[name='CCards'] option:selected").index();
+1  A: 
<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').value;

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


</script>
Alex
+1  A: 

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

$('select').change(function(){
    alert($('option:selected',$(this)).index());
});

Try it out --> http://jsfiddle.net/96s6n/

Jamiec
+1  A: 

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);
lincolnk
+1  A: 

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 
RoToRa