简体   繁体   中英

How to get the position of a selected option in a dropdown

How do I use jquery to find the position of the currently selected option, it also needs to update in real time if the user selects a different option.

 <select id="visa_type_c" title="" name="visa_type_c">
     <option selected="selected" value="No Visa" label="No Visa">No Visa</option>
     <option value="EU Visa" label="EU Visa">EU Visa</option>
     <option value="Easy Visa" label="Easy Visa">Easy Visa</option>
     <option value="Hard Visa" label="Hard Visa">Hard Visa</option>
 </select>

I seen the other threads but they are slightly different and I cant seem to make it work right for me.

Can just use pure JS:

document.getElementById("visa_type_c").onchange = function() {
    alert(this.selectedIndex);
}

Pure JS Demo: http://jsfiddle.net/Xxqnr/1/

$("select").on("change", function(ev) {
    console.log(ev.target.selectedIndex);
});
<a href='javascript:alert($("#visa_type_c option:selected").index())';>click for index</a>

Lots of ways to do it; if you add this to your page it will show you the selected index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM