Javascript Reference - HTML DOM Option selected Property








The selected property sets or gets the selected state of an option.

Browser Support

selected Yes Yes Yes Yes Yes

Syntax

Return the selected property.

var v = optionObject.selected 

Set the selected property.

optionObject.selected=true|false 

Property Values

Value Description
true|false Set the select state.
  • true - The option is selected
  • false - Default. The option is not selected




Return Value

A Boolean type value, true if the option is selected, otherwise false.

Example

The following code shows how to change the selected option in a drop-down list to "A".


<!DOCTYPE html>
<html>
<body>
<!--   w w  w. j  a  va  2s. c o  m-->
<form>
Select your favorite fruit:
<select>
  <option id="C">C</option>
  <option id="A">A</option>
  <option id="P" selected>P</option> // Pre-selected
  <option id="B">B</option>
</select>
</form>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("A").selected = "true";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to check if the "B" option in a drop-down list is selected.


<!DOCTYPE html>
<html>
<body>
<!--  ww w.java 2s.  co  m-->
Select your favorite fruit:
<br>
<select size="4">
  <option id="C" selected>C</option>
  <option id="A">A</option>
  <option id="P">P</option>
  <option id="B">B</option>
</select>
<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("B").selected;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows: