How to display JSON data in a select box using jQuery?
This is my JSON data:
{
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"开发者_StackOverflow社区SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria"
}
How to display this JSON data in a selectlist?
Use $.each and iterate over all your elements. This should work:
$.each(jsonData, function(key, value)
{
$('<option></option>').val(key).text(value).appendTo('#yourSelectList');
});
Here's one way (takes fewer function calls):
var myJson = {
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria"
};
$.each(myJson, function(key, val) {
$('#mySelect').append('<option value="' + key + '">' + val + '</option>');
});
精彩评论