Skip to content

Instantly share code, notes, and snippets.

@danrichards
Last active February 21, 2016 07:25
Show Gist options
  • Save danrichards/c0492a6b81ea930dacaa to your computer and use it in GitHub Desktop.
Save danrichards/c0492a6b81ea930dacaa to your computer and use it in GitHub Desktop.
$.populate(form, obj) Provided a selector and object, set the corresponding form fields.
/**
* Provided a data Object, set the corresponding form fields.
*
* @param obj Object Your data.
* @return Array Fields updated.
*/
$.fn.populate = function(obj) {
var updated = [];
for (var field in obj) {
var changes = false;
if (! obj.hasOwnProperty(field)) {
continue;
}
/**
* Try and set radio input fields
*/
var value = obj[field];
var values = $.isArray(value) ? value : [value];
var inputs = this.find('input[type=radio][name='+field+']');
if (inputs.length) {
$.each(inputs, function() {
var input = $(this);
if (input.val() == value) {
input.prop('checked', true);
} else {
input.prop('checked', false);
}
updated.push(field);
changes = true;
});
}
if (changes) {
continue;
}
/**
* Try and set checkbox input fields
*/
inputs = this.find('input[type=checkbox][name='+field+']');
if (inputs.length) {
$.each(inputs, function() {
var input = $(this);
var inputValue = input.val();
if ($.inArray(inputValue, values) > -1) {
input.prop('checked', true);
console.log('checked', inputValue, values);
} else {
input.prop('checked', false);
console.log('unchecked', inputValue, values);
}
updated.push(field);
changes = true;
});
}
if (changes) {
continue;
}
/**
* Try and set select multiple
*/
inputs = this.find('select[name='+field+'][multiple]');
if (inputs.length) {
$.each(inputs, function() {
var input = $(this);
var opts = input.find('option');
$.each(opts, function() {
var opt = $(this);
var optValue = opt.val();
if ($.inArray(optValue, values) > -1) {
console.log('selected', optValue, values);
opt.prop('selected', true);
} else {
console.log('unselected', optValue, values);
opt.prop('selected', false);
}
});
updated.push(field);
changes = true;
});
}
if (changes) {
continue;
}
/**
* Try and set select, textarea, or any other type of input fields
*/
inputs = this.find(
'input[name='+field+'],' +
'textarea[name='+field+'],' +
'select[name='+field+']'
);
if (inputs.length) {
inputs.val(value);
updated.push(field);
}
}
return $.unique(updated);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment