Select selectedIndex Property - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Select

Description

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

The index starts at 0.

The value "-1" clear the selection.

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

Set the selectedIndex property with the following Values

Value Description
number Sets the index of the selected option in a drop-down list

Return Value

A Number, representing the index of the selected option in the drop-down list.

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

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<select id="mySelect">
  <option>CSS</option>
  <option>Javascript</option>
  <option>Database</option>
  <option>SQL</option>
</select>//from   w w  w.j  a v a2 s  . c  o m

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

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

</body>
</html>

Related Tutorials