Javascript DOM HTML Select selectedIndex Property set

Introduction

Select the <option> element with index "2":

document.getElementById("mySelect").selectedIndex = "2";

Click the button to select the option element with index "2".

The index starts at 0.

View in separate window

<!DOCTYPE html>
<html>
<body>

<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>//ww w  . jav a2 s  .c  om

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {
  document.getElementById("mySelect").selectedIndex = "2";
}
</script>

</body>
</html>

The selectedIndex property sets or gets the index of the selected option in a drop-down list.

The index starts at 0.

If the drop-down list allows multiple selections it will only return the first selected index.

The value "-1" will deselect all options.

If no option is selected, the selectedIndex property will return -1.




PreviousNext

Related