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

HTMLJavascriptProgramming Scripts

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 −

Live Demo

<!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>
raja
Published on 26-Feb-2018 13:25:06
Advertisements