Jquery Ajax Populate Dropdown With Json Response Data
I know there are quite a few questions floating on this but I'm still not sure what to do. I have a HTML form called 'CuisineForm', after the user selects the type of cuisine, the
Solution 1:
Heres a fiddle that contains the full answer
HTML:
<select name="breakfast"id="breakfast"></select>
<select name="lunch"id="lunch"></select>
<select name="dinner"id="dinner"></select>
JS:
var data = {"breakfast":[{"09:00:00":"9:00 am"},{"09:30:00":"9:30 am"}],"lunch": [{"12:00:00":"12:00 pm"},{"12:30:00":"12:30 pm"}],"dinner":[{"19:00:00":"7:00 pm"},{"19:30:00":"7:30 pm"}]};
// Put this code inside of the "done callback"var $elements = $('#breakfast, #lunch, #dinner');
$.each(data, function (dataKey, dataVal) {
$elements.each(function(domElKey, domElVal){
if (dataKey === domElVal.id) {
$.each(dataVal, function(timeKey,timeVal){
$.each(timeVal,function(timePropKey, timePropVal){
$(domElVal).append("<option>"+timePropVal+"</option>");
});
})
}
});
});
Solution 2:
You could use the $.each()
function to loop through the data:
.done(function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
})
Assuming your server side script doesn't set the proper Content-Type: application/json
response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter
.
Post a Comment for "Jquery Ajax Populate Dropdown With Json Response Data"