I get ajax response as JSON and need to fill a form with it. How to do that in jQuery or something else ? Is something better than using $(json).each()
?
Pretty simple in pure JavaScript:
https://jsfiddle.net/ryanpcmcquen/u8v47hy9/
var data = {
foo: 1,
bar: 2
};
var inputs = Array.prototype.slice.call(document.querySelectorAll('form input'));
Object.keys(data).map(function (dataItem) {
inputs.map(function (inputItem) {
return (inputItem.name === dataItem) ? (inputItem.value = data[dataItem]) : false;
});
});
Edit: This also works with other inputs such as select
, simply by replacing document.querySelectorAll('form input')
with document.querySelectorAll('form input, form select')
.
This also gets around the global leak in this answer: https://stackoverflow.com/a/6937576/2662028