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() ?
jQuery Populate plugin and code proposed by @Mathias inspired me to make my own plugin:
Here my myPopulate plugin code. It use attr parameter as name of elements attribute on to use for identifying them.
(function($) {
$.fn.myPopulate = function(json, attr) {
var form = $(this);
$.each(json, function(key, value) {
form.children('[' + attr + '="' + key + '"]').val(value);
});
};
})(jQuery);
Using:
{
"id" : 12,
"name": "Jack",
"description": "Description"
}
form1 (matching by name attribute):
$('#form1').myPopulate(json, 'name');
form2 (matching by alt attribute):
$('#form2').myPopulate(json, 'alt');