Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and initialize an array with key/values using JavaScript and then dynamically creating select dropdown

Tags:

javascript

How to declare and initialize an array with key/values using JavaScript and then dynamically creating select dropdown and assigning key/values to the options using JavaScript?

Thanks

like image 676
Karim Ali Avatar asked Mar 25 '11 16:03

Karim Ali


1 Answers

It would be easier if you use JQuery... This is how it would be done in basic Javascript.

<html>
    <body>
        <span id="selectContainer"></span>
    </body>
    <script type="text/javascript">
        var selectItems = {
            me: "Hari Gangadharan",
            friend1: "Asif Aktar",
            friend2: "Jay Thomas",
            friend3: "John Abrams"
        }

        selectItems["newFriend"] = "Niel Goldman";

        var selectContainer = document.getElementById("selectContainer");
        var selectBox = document.createElement("SELECT");
    selectBox.id = selectBox.name = "friendList";
        selectContainer.appendChild(selectBox);
        for (var key in selectItems) {
            var value = selectItems[key];
            var option = document.createElement("OPTION");
            option.text = value;
            option.value = key;
            selectBox.options.add(option);
        }
    </script>
</html>
like image 100
Hari Gangadharan Avatar answered Oct 23 '22 06:10

Hari Gangadharan