Sara Ree
Sara Ree

Reputation: 3543

How to get the position of selected item in the select box

I want to return the position of the selected item in the select box not the value:

Here is what I'm trying but I think this could be impossible:

const selectBox = document.getElementById('selectBox');

function selectClicked() {
    console.log(selectBox.value); // this is the value but I want the position
}
<select id="selectBox" onclick="selectClicked()" size="10">
  <option>0</option> 
  <option>0</option>
  <option>0</option>
  <option>0</option>
  <option>0</option>
  <option>0</option>
</select>

Upvotes: 0

Views: 326

Answers (2)

Vitor M. Barbosa
Vitor M. Barbosa

Reputation: 3646

This gets the position of the clicked option (with as little modification to OP's code as possible).

const selectBox = document.getElementById('selectBox');

function selectClicked() {
    console.log(selectBox.selectedIndex); // position starting from 0
}
<select id="selectBox" onclick="selectClicked()" size="10">
  <option>0</option> 
  <option>0</option>
  <option>0</option>
  <option>0</option>
  <option>0</option>
  <option>0</option>
</select>

Upvotes: 0

caramba
caramba

Reputation: 22490

Not sure if you want the value or the selected index or just the text of the selected item. Following will cover them all. See comments in code

document.getElementById('selectBox').addEventListener(
    'change', // you need to listen on "change" event not "click" event
    function(event) {
        console.log(
            'selectedIndex: ' + event.target.selectedIndex, // it's zero indexed, which means the first item will be 0
            ' | value: ' + event.target.value,
            ' | text: ' + this.options[event.target.selectedIndex].text
        );
    }
);
<select id="selectBox" size="10">
  <option value="zero">ZERO</option> 
  <option value="one">ONE</option> 
  <option value="two">TWO</option> 
  <option value="three">THREE</option> 
  <option value="four">FOUR</option> 
  <option value="five">FIVE</option> 
</select>

Upvotes: 1

Related Questions