Javascript DOM HTML Select selectedIndex return -1 if no options are selected

Introduction

The selectedIndex property will return "-1" if no options are selected:

var x = document.getElementById("mySelect").selectedIndex;

View in separate window

<!DOCTYPE html>
<html>
<body>
<select id="mySelect" size="4">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>//from w  ww  .j  a  va 2  s  . c  o m
<p id="demo"></p>
<button type="button" onclick="myFunction()">Display index</button>

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

</body>
</html>



PreviousNext

Related