Using jquery, I am trying to populate a select drop-down with json. I am trying to display a list of countries from the json below...
{
"country":[
{
"China":[
{
"tarrifType":"Pay as you go"
},
{
"fixLine":"23p"
}
],
"India":[
{
"sms":"39p"
},
{
"fixLine":"3p",
"sms":"59p"
}
],
"Poland":[
{
"mobile":"29p",
"sms":"19p"
},
{
"tarrifType":"China Pass",
"fixLine":"23p"
}
]
}
]
}
So far the jquery I have tried to do this with is the following...
$.getJSON("js/widgets/country-picker.json", function(result){
$.each(result, function(i, field) {
$('#js-rate-select').append($('<option>').text(field[1]).attr('value', field[1]));
});
});
But it does not fill the select dropdown or give any DOM errors. Any suggestions how I can fix this? I think the issue is because of the json format - which I am able to change Thanks
Your json feed returns an array containing only one index, which is an object with the different countries. Therefor, you should say
result.country[0].China.tarrifType.
And, you would be able to iterate the countries like this:
$.each(result.country[0], function(country,data) { console.log(country); }
Although, i would recommend to redo your JSON. You could do like this:
var result = {
"country": {
"China": {
"tarrifType": "Pay as you go",
"fixLine": "23p"
},
"India": {
"sms": "39p",
"fixLine": "3p",
"sms": "59p"
},
"Poland": {
"mobile": "29p",
"sms": "19p",
"tarrifType": "China Pass",
"fixLine": "23p"
}
}
};
$(function () {
$.each(result.country, function (country, data) {
console.log("Country : " + country);
console.log(data); // data.fixLine, data.tarrifType, data.sms
$('#selectbox').append('<option value="' + country + '">' + country + '</option>');
});
});
jsfiddle here: Link to JSfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With