Reputation: 2174
i have json data, i want to populate this values into select-box.. I tried(FIDDLE) below code but its NOT populating drop-down, please help me.
var obj=
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
"AMD": "Armenian Dram",
"XOF": "CFA Franc BCEAO",
"XPF": "CFP Franc",
"YER": "Yemeni Rial",
"ZAR": "South African Rand",
"ZMK": "Zambian Kwacha (pre-2013)",
"ZMW": "Zambian Kwacha",
"ZWL": "Zimbabwean Dollar"
};
for(var i=0;i<obj.length;i++)
{
var option=$('<option></option>').text(obj.[i]);
$('select').append(option);
}
html
<select></select>
Upvotes: 0
Views: 679
Reputation: 422
Object members cannot be accessed with numeric subscripts (unless their keys happen to be numbers); you must use their keys instead. There is a very simple syntax for iterating through an object's keys:
for (var key in obj) {
var option=$('<option></option>').text(obj[key]);
$('select').append(option);
}
Upvotes: 2
Reputation: 3284
All of the answers will work, as mentioned, you are trying to access an object as though it were an array. here is mine:
var keys = Object.keys(obj);
for(var i=0;i<keys.length;i++)
{
var option= $('<option value="' + keys[i] + '">' + obj[keys[i]] + '</option>');
$('select').append(option);
}
on jsfiddle: http://jsfiddle.net/5czG4/75/
Upvotes: 1
Reputation: 3110
Try this:
for (var o in obj) {
var option=$('<option></option>').text(obj[o]);
$('select').append(option);
}
You might want values for each option too:
for (var o in obj) {
var option=$('<option></option>').val(o).text(obj[o]);
$('select').append(option);
}
Fiddle: http://jsfiddle.net/5czG4/77/
Upvotes: 3
Reputation: 2804
There's no dot in obj[i]
.
And since you're using jQuery you can do:
$.each(obj, function(key, value){
$select.append( $("<option value='" + key + "'>" + value + "</option") );
});
Upvotes: 2