Skip to content

Instantly share code, notes, and snippets.

@crswll
Last active December 31, 2015 00:09
Show Gist options
  • Save crswll/7905125 to your computer and use it in GitHub Desktop.
Save crswll/7905125 to your computer and use it in GitHub Desktop.
The data parameter needs to be the format of jQuery's .serializeArray(), which makes this really useful for cloning a form and keeping the input values in tact.
var populate = function ($form, data) {
var $inputs = $form.find(':input');
$.each( data, function (idx, field) {
var $ctrl = $inputs.filter(function(){
return this.name === field.name;
});
var value = field.value;
var type = $ctrl.attr('type') ? $ctrl.attr('type') : 'text';
switch (type) {
case "radio":
case "checkbox":
$ctrl.each(function(){
var $this = $(this);
if( $this.val() === value ){
$this.prop('checked', true);
}
});
break;
default:
$ctrl.val( value );
break;
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment