Javascript Form How to - Refer to a selected item in a dropdown menu using DOM








Question

We would like to know how to refer to a selected item in a dropdown menu using DOM.

Answer


<!DOCTYPE html>
<html>
<body>
  <select id="My_Select_Menu">
    <option value="Blue" selected="selected">blue</option>
  </select>
    <script type='text/javascript'>
    <!-- w ww. java2  s.  c o m-->
        var sel = document.getElementById("My_Select_Menu");
        if (sel.options[sel.selectedIndex].value == "Blue") {
            console.log("hahaha");
        }
    
    </script>
</body>
</html>

The code above is rendered as follows: