Option selected Property - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Option

Description

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

Set the selected property with the following Values

Value Description
true|false Sets whether an option in a drop-down list should be selected.

Return Value

A Boolean, returns true if the option is selected, otherwise it returns false

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

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<form>
Select your favorite fruit:
<select>
  <option id="a">Apple</option>
  <option id="orange">Orange</option>
  <option id="pineapple" selected>Pineapple</option> // Pre-selected
  <option id="banana">Banana</option>
</select>//from   w  ww  . j  a v  a  2 s. c o m
</form>

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

<script>
function myFunction() {
    document.getElementById("orange").selected = "true";
}
</script>

</body>
</html>

Related Tutorials