Skip to content

Instantly share code, notes, and snippets.

@element6
Created October 14, 2015 06:16
Show Gist options
  • Save element6/f5f4627a137dd16dbf79 to your computer and use it in GitHub Desktop.
Save element6/f5f4627a137dd16dbf79 to your computer and use it in GitHub Desktop.
get or restore form values
//$('form').values() or $('form').values(v)
$.fn.values = function(data) {
var els = $(this).find(':input').get();
if (typeof data != 'object') {
// return all data
data = {};
$.each(els, function() {
if (this.name && !this.disabled && (this.checked
|| /select|textarea/i.test(this.nodeName)
|| /text|number|hidden|password/i.test(this.type))) {
if (this.type === 'checkbox' || this.type === 'radio') {
//multiple values goes into the same key
data[this.name] = data[this.name] || {};
data[this.name][$(this).val()] = true;
} else {
data[this.name] = $(this).val();
}
}
});
return data;
} else {
$.each(els, function() {
if (this.name && data[this.name]) {
if (this.type === 'checkbox' || this.type === 'radio') {
$(this).prop("checked", $(this).val() in data[this.name]);
} else {
$(this).val(data[this.name]);
}
}
});
return $(this);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment