How To Get The Selected Index Of A Drop Down August 20, 2024 Post a Comment 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. Solution 1: $("select[name='CCards'] option:selected") should do the trickSee 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() CopySolution 2: This will get the index of the selected option on change:$('select').change(function(){ console.log($('option:selected',this).index()); });Copy<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectname="CCards"><optionvalue="0">Select Saved Payment Method:</option><optionvalue="1846">test xxxx1234</option><optionvalue="1962">test2 xxxx3456</option></select>CopySolution 3: If you are actually looking for the index number (and not the value) of the selected option then it would bedocument.forms[0].elements["CCards"].selectedIndex/* You may need to change document.forms[0] to reference the correct form */Copyor using jQuery$('select[name="CCards"]')[0].selectedIndexCopySolution 4: the actual index is available as a property of the select element.var sel = document.getElementById('CCards'); alert(sel.selectedIndex); Copyyou 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); CopySolution 5: <selectname="CCards"id="ccards"><optionvalue="0">Select Saved Payment Method:</option><optionvalue="1846">test xxxx1234</option><optionvalue="1962">test2 xxxx3456</option></select><scripttype="text/javascript">/** Jquery **/var selectedValue = $('#ccards').val(); //** Regular Javascript **/var selectedValue2 = document.getElementById('ccards').value; </script>Copy Share Post a Comment for "How To Get The Selected Index Of A Drop Down"
Post a Comment for "How To Get The Selected Index Of A Drop Down"