Javascript DOM HTML Option selected Property set

Introduction

Change the selected option in a drop-down list to "orange":

document.getElementById("orange").selected = true;

Click the button to change the selected option to "orange".

View in separate window

<!DOCTYPE html>
<html>
<body>

<form>
  Select your favorite:
  <select>
    <option id="apple">Apple</option>
    <option id="orange">Orange</option>
    <option id="pineapple" selected>Pineapple</option> // Pre-selected
    <option id="banana">Banana</option>
  </select>
</form>//from   w  w w. j  a v  a  2  s  . co m
<button onclick="myFunction()">Test</button>

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

</body>
</html>

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

Value Description
true The option is selected
false Default. The option is not selected

The selected property returns true if the option is selected, otherwise it returns false.




PreviousNext

Related