Get the ID of an option in select dropdown

Viewed 54

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)

2 Answers

Use the selectedIndex to get this.

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