HTML Dropdown List

HTML Dropdown List

An HTML Dropdown List is a control that provides a menu of options.

It is a form and an inline element.

The <select> element defines an HTML Dropdown List.

It should enclose multiple <option> elements with the value attribute for each

HTML Dropdown Attribute

  • multiple : specifies whether multiple options can be selected from a dropdown list; this attribute not require a value, it only needs to be present at the start tag
💡 You will learn more attribute that can be used with a dropdown list on our HTML5 Form Elements Attribute lesson.

💡With JavaScript we can easily get the value/s of a <select> element, to see hoe to do that simply click on each of the "Try it Yourself" button.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML Dropdown List </title>
</head>
<body>
    <select id="sample">
        <option value="Apples"> Apples </option>
        <option value="Oranges"> Oranges </option>
        <option value="Grapes"> Grapes </option>
        <option value="Bananas"> Bananas </option>
        <option value="Strawberries"> Strawberries </option>
    </select>
    <button onclick="getValue();"> Get Value </button>
    <script type="text/javascript">
        function getValue(){
            var value = document.getElementById('sample').value;
            alert(value);
        }
    </script>
</body>
</html>

Output:



Multiple Options Allowed Example:

<!DOCTYPE html>
<head>
    <title>HTML Dropdown List </title>
</head>
<body>
    <select id="sample" multiple>
        <option value="Apples"> Apples </option>
        <option value="Oranges"> Oranges </option>
        <option value="Grapes"> Grapes </option>
        <option value="Bananas"> Bananas </option>
        <option value="Strawberries"> Strawberries </option>
    </select>
    <button onclick="getValues();"> Get Values </button>
    <script type="text/javascript">
        function getValues(){
            var options = document.getElementById('sample').options;
            var options_count = document.getElementById('sample').options.length;
            var value = [];

            for (var i = 0; i < options_count; i++) {
                if(options[i].selected){
                value.push(options[i].value);
                }               
            }
            alert(JSON.stringify(value));
        }
    </script>
</body>
</html>

Output:



    
                                                                                

Post a Comment

Post a Comment (0)