Reputation: 4617
I am trying to generate an HTML select menu using a javascript array. The array keys should be used as values of options. And if the array keys are entered as numbers(as what I have done in my code) they should be accepted.
a([selected="No of rooms", 1="1", 2="2", 3="3", 4="4", 5="5"]);
function a(x) {
elementString = "<select>";
for(var i in x) {
elementString += '<option value="">'+i+'</option>';
}
elementString += "</select>";
alert(elementString);
}
But this code does not work. And I could not find a way to use array keys as the values of options. Another question I got is, if I put numbers as keys it does not work(This is a requirement).
Edit: jsfiddle link works now
Upvotes: 2
Views: 535
Reputation: 144719
Your code is syntactically wrong and JavaScript doesn't have associative arrays, the key of array's elements is their index, however you can use an object:
a({selected: "No of rooms", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5"});
But it should be noted that JavaScript object doesn't have order, ie, the generated elements may be different in each browser. If you want to keep the order you should use an array, in this case an array of objects:
a([{
text: "No of rooms",
value: "...",
selected: true
}, {
text: "one",
value: "1",
selected: false
}]);
function a(x) {
var elementString = "<select>";
for (var i = 0; i < x.length; i++) {
elementString += '<option value="' + x[i].value + '"' + (x[i].selected ? "selected='selected'" : '') + '>' + x[i].text + '</option>';
}
elementString += "</select>";
// document.body.innerHTML = (elementString);
}
Upvotes: 2
Reputation: 43166
The syntax of your array is wrong.
check this fiddle
change your array as follows
var arr= ["No of rooms", "1", "2", "3", "4", "5"];
if you want to use key- value pairs, use an array of json objects.
update: fiddle using json
var arr = [{
value: '1',
data: "1"
}, {
value: '2',
data: "2"
}, {
value: '3',
data: "3"
}, {
value: '4',
data: "4"
}, {
value: '4',
data: "4"
}];
a(arr);
function a(x) {
elementString = "<select><option value='0' selected>" + "No of rooms</option>";
for (var i in x) {
elementString += '<option value="' + x[i].value + '">' + x[i].data + '</option>';
}
elementString += "</select>";
alert(elementString);
}
Upvotes: 1
Reputation: 113
If you have assoc massive like var arr={"room1" : "1", "room2" : "2"}
then you can use keys of array like new array:
var keys = Object.keys(arr);
var k = keys.length;
var elementString = "<select>";
for(var i=0; i<k; i++) {
elementString += '<option value="'+keys[i]+'">'+arr[keys[i]]+'</option>';
}
elementString += "</select>";
And more simple method is:
var arr = {"room1" : "1", "room2" : 2};
for (var i in arr) {
elementString += '<option value="'+i+'">'+arr[i]+'</option>';
}
elementString += "</select>";
Upvotes: 2