Computer >> Computer tutorials >  >> Programming >> Javascript

How to show the index of the selected option in a dropdown list with JavaScript?


To show the index of the selected option in a drop-down list, use the selectedIndex property in JavaScript.

Example

You can try to run the following code to display the index of the selected option −

<!DOCTYPE html>
<html>
   <body>
      <form id="myForm">
         <select id="selectNow">
            <option>One</option>
            <option>Two</option>
            <option>Three</option>
          </select>
          <input type="button" onclick="display()" value="Click">
      </form>
      <p>Select and click the button to get the index of the selected option.</p>
      <script>
         function display() {
            var index = document.getElementById("selectNow").selectedIndex;
            document.write(index);
         }
      </script>
   </body>
</html>