简体   繁体   中英

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>

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>

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>

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