Connor Bishop Connor Bishop - 3 months ago 7x
Ajax Question

A quicker way to update lots of values

Im updating many fields using ajax. My server is getting a row from the database then I am JSON encoding the row and sending this as my xmlhttp.responseText.

The response text is of the form

{"JobCardNum":5063,"IssueTo":"MachineShop","Priority":"High" ...lots of data}

In the browser I then JSON parse the response text and then begin the long process of updating the values like so:

var obj = JSON.parse(info);
document.getElementById("JobCardNum").value = obj.JobCardNum;
document.getElementById("IssueTo").value = obj.IssueTo;
document.getElementById("MachineShop").value = obj.MachineShop;
....... lots of similar statements

As the element id matches the column names I though there might be a way to loop through my JavaScript object and set all my values. Any Ideas?


The solution using Object.keys and Array.forEach functions:

var obj = JSON.parse(info);

    var el = document.getElementById(id);
    if (el) el.value = obj[id];