The selectedIndex
property sets or gets the index of the selected option in a drop-down list.
The index starts at 0.
selectedIndex |
Yes | Yes | Yes | Yes | Yes |
Return the selectedIndex property.
var v = selectObject.selectedIndex
Set the selectedIndex property.
selectObject.selectedIndex=number
Value | Description |
---|---|
number | Set the index of the selected option in a drop-down list |
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.
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:
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:
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:
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: