I know there is a far more elegant/efficient way of doing this (in php I would use foreach) but with jQuery how can I walk the var/val pairs of a JSON response and populate
If your results looks like this:
[{"field1":"value1","field2":"value2"}]
Then the code provided by Seb and Chetan works
$.each(data, function(i, item){
$("#"+item.field).val(item.value);
});
If your results looks like this:
{"field1":"value1","field2":"value2"}
Then use this code
$.each(data, function(field, value){
$("#"+field).val(value);
});
You can get rid of all "if" statements by replacing your $.each with this:
$.each(data, function(i, item){
$("#"+item.field).val(item.value);
});
I noticed that element IDs are the same as fields in your JSON, how about:
$(document).ready(function() {
$('#svendor_name').bind("change", function()
{
var svendor = $("#svendor_name").val();
svendor = svendor.replace(/&/g, '*');
$.getJSON("get_vendors.php?sname=" + svendor,
function(data) {
$.each(data, function(i, item) {
$('#' + item.field).val(item.value);
});
});
});
});
What is wrong with this?
$.each(data,
function(i, item) {
$("#" + item.field).val(item.value);
}
});