Thanks to Barnabas Kendall for initial function and Eggert Jóhannesson for radio button fix!
I encountered an issue with checkboxes, if they are not checked they won't be put into the array, so far so good. But as the state of checkboxes is not stored when they are not checked I couldn't restore this state if the user had checked them during editing the form.
So I extended the restore functionality to uncheck all checkboxes which are not in the data array, this will ensure the state of checkboxes is restored correctly no matter what was changed in the form before executing restore:
if (this.name && data[this.name]) {
if(this.type == "checkbox" || this.type == "radio") {
$(this).prop("checked", (data[this.name] == $(this).val()));
} else {
$(this).val(data[this.name]);
}
} else if (this.type == "checkbox") {
$(this).prop("checked", false);
}
Complete function:
$.fn.values = function(data) {
var inps = $(this).find(":input").get();
if(typeof data != "object") {
// return all data
data = {};
$.each(inps, function() {
if (this.name && (this.checked
|| /select|textarea/i.test(this.nodeName)
|| /text|hidden|password/i.test(this.type))) {
data[this.name] = $(this).val();
}
});
return data;
} else {
$.each(inps, function() {
if (this.name && data[this.name]) {
if(this.type == "checkbox" || this.type == "radio") {
$(this).prop("checked", (data[this.name] == $(this).val()));
} else {
$(this).val(data[this.name]);
}
} else if (this.type == "checkbox") {
$(this).prop("checked", false);
}
});
return $(this);
}
};