views:

117

answers:

1

The example ajax form

<form method="post">
  <input type="text" name="name" />
  <input type="text" name="email" />
  <select name="group">
    <option value="1">group 1</option>
    <option value="2">group 2</option>
  </select>
  <button type="submit">submit</button>
</form>

each time the form is show an ajax call is sent and the server returns a json object like

{"name":"john", "email": "[email protected]", "group": 2}

I don't want to do the tedious work of filling the form with the json data manually, is there any jquery plugin can help me do this, with 1 line of code? e.g

$('#myform').fillWith( json );

Thanks.

+2  A: 

You could easily build a simple plugin to do so:

jQuery.fn.fillWith = function(input) {
  return this.each(function(){
    var form = this;
    $.each(input, function (key, value) {
      $(form).find('[name='+key+']').val(value);
    });
  });
};

You may want to optimize the attribute selector, to check only for input, select, textarea elements, in this example the selector is looking for any element (*[name=foo]).

Also you might have to add some code to handle radio buttons correctly.

Check an example with your markup here.

CMS
+1 for being quicker
munch