Javascript DOM HTML Option index Property get text and index

Introduction

Display the text and index of all options in a drop-down list:

Click the button to display the text and index of all options in the dropdown list.

View in separate window

<!DOCTYPE html>
<html>
<body>

Select your favorite:
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>//from   w  w w .  j  a  v a2  s .  com
<p id="demo"></p>
<button type="button" onclick="myFunction()">Test</button>

<script>
function myFunction() {
  var x = document.getElementById("mySelect");
  var txt = "All options: ";
  var i;
  for (i = 0; i < x.length; i++) {
    txt = txt + "<br>" + x.options[i].text + " has index: " + x.options[i].index;
  }

  document.getElementById("demo").innerHTML =txt;
}
</script>

</body>
</html>



PreviousNext

Related