Javascript DOM HTML Select selectedIndex get index and text

Introduction

Display the index and text of the selected option in a drop-down list:

View in separate window

<!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  w  w w .j a v  a 2 s . c  om*/
<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>



PreviousNext

Related