0

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>

Dan
  • 2,086
  • 11
  • 71
  • 137
  • 1
    Your object is not an array, and therefore cannot be used with an indexer. Have you tried using a for each loop? – xDaevax Aug 26 '14 at 20:46
  • Please don't forget to select one as the answer. – Matthew Graves Aug 26 '14 at 20:48
  • possible duplicate of [What is the best way to add options to a select from an array with jQuery?](http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery) – Dalorzo Aug 26 '14 at 20:53

4 Answers4

3

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/

Slippery Pete
  • 3,051
  • 1
  • 13
  • 15
2

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") );
});
aldux
  • 2,774
  • 2
  • 25
  • 36
2

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);
}
Colin P. Hill
  • 422
  • 4
  • 18
1

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/

Matthew Graves
  • 3,226
  • 1
  • 17
  • 20