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 form fields with the same id's as the field names in the JSON response?
Here is my JSON response:
[{"field":"svendor_name","value":"Vendor Name Inc."},{"field":"svendor_addr1","value":"1234 Vendor Lane."},{"field":"svendor_addr2","value":"Suite 100"},{"field":"svendor_city"
,"value":"Vendorville"},{"field":"svendor_state","value":"CA"},{"field":"svendor_zip","value":"90210"},{"field"
:"svendor_phone","value":"800-555-1234"}]
Here is my jQuery code for populating the form:
$(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)
{
if(item.field == "svendor_name")
{
$("#svendor_name").val(item.value);
}
else if(item.field == "svendor_addr1")
{
$("#svendor_addr1").val(item.value);
}
else if(item.field == "svendor_addr2")
{
$("#svendor_addr2").val(item.value);
}
else if(item.field == "svendor_city")
{
$("#svendor_city").val(item.value);
}
else if(item.field == "svendor_state")
{
$("#svendor_state").val(item.value);
}
else if(item.field == "svendor_zip")
{
$("#svendor_zip").val(item.value);
}
else if(item.field == "svendor_phone")
{
$("#svendor_phone").val(item.value);
}
else if(item.field == "svendor_id")
{
$("#svendor_id").val(item.value);
}
});
});
});
});
That all works fine and good but I really want to avoid all the if/else statements and just use the data coming back from the getJSON method to determine what fields get populated with what values. What is a cleaner/more effective approach to this?
-- Nicholas
You can get rid of all "if" statements by replacing your $.each with this:
$.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);
}
});
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