Display the index and text of the selected option in a drop-down list:
<!DOCTYPE html> <html> <body> Select a fruit and click the button: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select>/*from ww w . j av a2 s. c o m*/ <p id="demo"></p> <button type="button" onclick="myFunction()">Display index</button> <script> function myFunction() { var x = document.getElementById("mySelect").selectedIndex; var y = document.getElementById("mySelect").options; document.getElementById("demo").innerHTML ="Index: " + y[x].index + " is " + y[x].text; } </script> </body> </html>
The index property sets or gets the index position of an option in a drop-down list.
The index starts at 0.
Value | Description |
---|---|
integer | Specifies the index position of the option within a drop-down list |
The index property returns a number representing the index position of the option within a drop-down list.