Highlight popup menu with json
Using jquery I am trying to populate a dropdown using json. I am trying to display a list of countries from 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 doesn't populate the select dropdown or give any DOM errors. Any suggestions how I can fix this? I think the problem is with the json format, which I can change. Thank.
+3
Jose the hose
source
to share
1 answer
Your json feed is returning an array containing only one index, which is an object with different countries. So you have to say
result.country[0].China.tarrifType.
And you could repeat the following countries:
$.each(result.country[0], function(country,data) { console.log(country); }
Although, I would recommend repeating your JSON. You can do the following:
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: JSfiddle link
+2
Jonas m
source
to share