Javascript Reference - HTML DOM Select selectedIndex Property








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

The index starts at 0.

Browser Support

selectedIndex Yes Yes Yes Yes Yes

Syntax

Return the selectedIndex property.

var v = selectObject.selectedIndex

Set the selectedIndex property.

selectObject.selectedIndex=number

Property Values

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




Return Value

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

The index starts at 0. If no option is selected, the value returned is -1.

Example

The following code shows how to get the index and text of the selected option in a drop-down list.


<!DOCTYPE html>
<html>
<body>
<!--from   ww  w  .ja v  a2s.c o m-->
Select a fruit and click the button:
<select id="mySelect">
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
</select>

<button type="button" onclick="myFunction()">Display index</button>

<script>
function myFunction() {
    var x = document.getElementById("mySelect").selectedIndex;
    var y = document.getElementById("mySelect").options;
    console.log("Index: " + y[x].index + " is " + y[x].text);
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to deselect all options.


<!DOCTYPE html>
<html>
<body>
<!--   w  w  w.  j a  v a2  s.co m-->
<select id="mySelect">
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
</select>
<button onclick="myFunction()">test</button>

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

</body>
</html>

The code above is rendered as follows:

Example 3

The selectedIndex property will return "-1" if no options are selected.


<!DOCTYPE html>
<html>
<body>
<select id="mySelect" size="4">
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
</select><!-- w w w .  j ava 2s .  c o m-->
<button type="button" onclick="myFunction()">Display index</button>
<script>
function myFunction() {
    var x = document.getElementById("mySelect").selectedIndex;
    console.log(x);
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to select the <option> element with index "2".


<!DOCTYPE html>
<html>
<body>
<!--from w w w . j av  a2 s . c  o  m-->
<select id="mySelect">
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
</select>
<button onclick="myFunction()">test</button>

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

</body>
</html>

The code above is rendered as follows: