简体   繁体   中英

Get the ID of an option in select dropdown

I have a select dropdown:

 <select onChange={(e)=> console.log(e.target.id)} id="cars" name="carlist" form="carform" > <option id="a" value="volvo"> Volvo </option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select>

I would like to get the ID a when selecting 'volvo' from the dropdown, thus getting the ID of the option , how can I achieve this?

The reason why I'm trying to get an id is because this dropdown can have multiply options with the same name (they would be separated by a line)

Use the selectedIndex to get this.

var getId = document.querySelector('#cars');
console.log(getId.options[getId.selectedIndex].id);

You can have the pass the reference of 'this' and get it from there. something like the below answer

How to get selected option ID with Javascript not JQuery


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