How to know the current position of an element in the option

1

<!DOCTYPE html>
<html>
<body>

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi" selected>Audi</option>
</select>

</body>
</html>

What javascript command can I use to get the position of the currently selected element in this "list" of options? Example: Volvo = 0 (because it is the first one on the list, so I imagine it to be 0), saab = 1.

    
asked by anonymous 04.05.2018 / 01:07

1 answer

1

You can use selectedIndex . It will return the index of option with the selected property:

var opt = document.body.querySelector("select").selectedIndex;
console.log(opt);
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi" selected>Audi</option>
</select>

If you want to put an event to pick up the index by changing the selection:

var sel = document.body.querySelector("select");

sel.addEventListener("change", function(){
   var opt = this.selectedIndex;
   console.log(opt);
});
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi" selected>Audi</option>
</select>
    
04.05.2018 / 01:10