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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With