Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  191] [ 3]  / answers: 1 / hits: 70031  / 13 Years ago, fri, march 25, 2011, 12:00:00

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


More From » javascript

 Answers
3

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>

[#93073] Thursday, March 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
triston

Total Points: 545
Total Questions: 88
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;