Question

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": "john@some-domain.com", "group": 2}

I don't want to do the tedious work of filling the form with the json data manually, e.g

$('#myform').fillWith( json );
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top