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

Asked

Viewed 63 times

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 (as it is the first on the list, so I imagine it to be 0), Saab = 1.

1 answer

1


Can use selectedIndex. Will return the index of option with the property selected:

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 place an event to pick the index when 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>

  • sorry, I made an edit. it’s about the element that is currently selected. Example: by default is the Audi, so if I do not change anything, must return 0 which is your position

  • Ok! Updated response

Browser other questions tagged

You are not signed in. Login or sign up in order to post.