-9

i have a array like follows

countries: [{
      "name": "Afghanistan",
      "cca2": "AF",
      "calling-code": "93"
    },
    //{"name":"Åland Islands","cca2":"AX","calling-code":"358"},
    {
      "name": "Albania",
      "cca2": "AL",
      "calling-code": "355"
    }, {
      "name": "Algeria",
      "cca2": "DZ",
      "calling-code": "213"
    }, {
      "name": "American Samoa",
      "cca2": "AS",
      "calling-code": "1684"
    }, {
      "name": "Andorra",
      "cca2": "AD",
      "calling-code": "376"
    }, {
      "name": "Angola",
      "cca2": "AO",
      "calling-code": "244"
    }, {
      "name": "Anguilla",
      "cca2": "AI",
      "calling-code": "1264"
    }, {
      "name": "Antigua and Barbuda",
      "cca2": "AG",
      "calling-code": "1268"
    }
     ]

i want to iterate through this list and create select list like follows

<select>
   <option value="AF">Afganisthan</option>
   ....
<select>

i did this

for (var i = 0; i < countries.length; i++) {
    out += "<option value='" + countries[i].cca2 + "'>" + countries[i].name + "</option>";
}

but nothing showing up..

Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

5 Answers5

0

Try this :

for(var i=0;i<countries.length;i++){
    $('select').append('<option value="'+countries[i].cca2+'">'+countries[i].name+'</option>');
}
darma
  • 4,687
  • 1
  • 24
  • 25
0
<select id='mySelect'><select>

$.each(countries, function(i, e){
    $('#mySelect').append("<option value='" + e.cca2 +"'>" + e.name + "</option>");
})

Demo

zs2020
  • 53,766
  • 29
  • 154
  • 219
0
    var obj = eval('{' + str + '}'); //where str is "countries: ..."
    $('<select>').appendTo(document.body);    
    for(var i = 0; i < obj.countries.length; i++)
    {
       $('<option>').val(obj.countries[i].cca2).text(obj.countries[i].name).appendTo('select');
    }
Daniil Grankin
  • 3,841
  • 2
  • 29
  • 39
0
var out = '<select>';

countries.forEach(function(country) {
    out += '<option value=' + country.cca2 + '>' + country.name + '</option>';
});

out += '</select>';
tjb1982
  • 2,257
  • 2
  • 26
  • 39
0

try the below javascript code snippet

var countryJSON= eval('{'+countryString+'}');
$('<select>').appendTo("#yourForm");    
for(i=0;i<countryJSON['countries'].length;i++){    
 $('<option>').val(countryJSON.countries[i].cca2).text(countryJSON.countries[i].name).appendTo('select');
}
Amith
  • 1,424
  • 1
  • 10
  • 22