Option defaultSelected Property - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Option

Description

The defaultSelected property returns the default value of the selected attribute.

Return Value

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

Check if the selected option is checked by default:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

Select your favorite fruit:
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option selected>Pineapple</option>
  <option>Banana</option>
</select>//from  w w w .  j a  v  a2s . c  om
<br>

<button type="button" onclick="myFunction()">Is selected fruit selected by default?</button>

<script>
function myFunction() {
    var x = document.getElementById("mySelect").selectedIndex;
    var y = document.getElementsByTagName("option");
    console.log("Is " + y[x].text + " selected by default? " + y[x].defaultSelected);
}
</script>

</body>
</html>

Related Tutorials