How to create a JavaScript drop-down list

Drop-down list (also referred to as a drop-down menu, a pull-down list, and a pick-list), is a common component or feature used on web pages to narrow down options offered by the web page. Here's a small  snippet of

JavaScript code that demonstrates how to create the drop-down list on a web page. 

The list options are stored in the array:
var listArrayOptions = new Array("Red", "Green", "Blue", "Black", "White","Yellow"); 
JavaScript code that populates the drop-down list:

for(var i = 0; i < listArrayOptions.length; i++) {
     var opt = listArrayOptions[i];
     select.innerHTML += "<option value=\"" + i + "\">" + opt + "</option>";
}


The code below is documented and easy to follow but if you have any question please leave a comment.



<!doctype html>
<html lang="en">
    <head>
        <title>JavaScript - Drop-down list demo</title>        
    </head>
    <body>
        <div style="border: 1px solid black; width:500px; padding:20px; margin:auto;">
            <h1>Dropdown List Demo</h1>
              <!-- Div tag to display button click results -->      
            <div id="displaySelection"></div>
            <br>
            <!-- Creating the dropdown list -->
            <select id="dropDownList"></select>
            <br><br>
            <!-- Button calling the GetSelectedValue() function -->
            <button onclick="GetSelectedValue()">
                Click to display selection 
            </button>
        </div>

        <script> 
            // list array  
            var listArrayOptions = new Array("Red", "Green", "Blue", "Black"
                                                                          , "White","Yellow"); 
            var dropDownListDom = document.getElementById("dropDownList");
            dropDownListDom.innerHTML = "";

            /* for loop to iterate the arry into the dropdown list 
             * i = index & opt = text
             * Select.innerHTML append the index and the text
             */
            for(var i = 0; i < listArrayOptions.length; i++) {
                    var textValue = listArrayOptions[i];
                    dropDownListDom.innerHTML += "<option value=\"" + i + "\">" 
                       + textValue + "</option>";
            }

            // Function, on button click the index number and the text value is displayed.  
            function GetSelectedValue() {
                var myPick = document.getElementById("dropDownList");
                var resultValue = myPick.options[myPick.selectedIndex].value;
                var resultText =  myPick.options[myPick.selectedIndex].text;    
                document.getElementById("displaySelection").innerHTML = 
                  "Selected index =>: "+ resultValue + " ----- " + "Selected text =>: " + resultText;
            }
        </script>

    </body>
</html>

No comments:

Post a Comment