jQuery The plugin plugin and code suggested by @Mathias inspired me to make my own plugin:
Here is my module code myPopulate. It uses the attr parameter as an attribute of the attribute name to use to identify 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 (match the name attribute):
<form> <input type="text" name="name" /> <input type="text" name="id" /> <textarea type="text" name="description" /> </form> $('#form1').myPopulate(json, 'name');
form2 (match the alt attribute):
<form id="form2"> <input type="text" name="nick" alt="name" /> <input type="text" name="identifier" alt="id" /> <textarea type="text" name="desc" alt="description" /> </form> $('#form2').myPopulate(json, 'alt');
source share