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()
?
You might also consider usage of jQuery templates for that purpose:
http://api.jquery.com/jQuery.template/
Just use a JSON plugin for jQuery - such as jquery-json.
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;
});
});
<form>
<input name="foo">
<input name="bar">
</form>
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
var json={
"id" : 12,
"name": "Jack",
"description": "Description"
};
for(key in json)
{
if(json.hasOwnProperty(key))
$('input[name='+key+']').val(json[key]);
}
srry i thought it was the id property that was set.
here: http://jsfiddle.net/anilkamath87/XspdN/
I haven't seen a solution that accounts for a form with nested properties. Here it is.
//pass in the parent object name, if there is one
let parentName = 'optional';
SyncJsonToForm(data, parentName);
function SyncJsonToForm(obj, path = '') {
let subpath = path === '' ? path : path + '.';
$.each(obj, function (key, value) {
let jsonPath = subpath + key;
// to debug a particular field (or multiple fields), replace the following JsonPath(s) with the desired property(ies)
if ([''].includes(jsonPath)) {
console.log(jsonPath);
debugger;
}
// update the value for the jsonPath
$(`[name="${jsonPath}"]`).val(value);
if (typeof value === "object") {
SyncJsonToForm(value, jsonPath);
}
});
}