I have a rather complicated form with many \"steps\" in it that are filled in by the user. Some steps (think of them as form segments) have default options, but on clicking
Here are a couple functions to help with this process. formToString
serializes a form as a string, and stringToForm
does the reverse:
function formToString(filledForm) {
formObject = new Object
filledForm.find("input, select, textarea").each(function() {
if (this.id) {
elem = $(this);
if (elem.attr("type") == 'checkbox' || elem.attr("type") == 'radio') {
formObject[this.id] = elem.attr("checked");
} else {
formObject[this.id] = elem.val();
}
}
});
formString = JSON.stringify(formObject);
return formString;
}
function stringToForm(formString, unfilledForm) {
formObject = JSON.parse(formString);
unfilledForm.find("input, select, textarea").each(function() {
if (this.id) {
id = this.id;
elem = $(this);
if (elem.attr("type") == "checkbox" || elem.attr("type") == "radio" ) {
elem.attr("checked", formObject[id]);
} else {
elem.val(formObject[id]);
}
}
});
}
Usage:
// Convert form to string
var formString = formToString($("#myForm"));
// Save string somewhere, e.g. localStorage
// ...
// Restore form from string
stringToForm(formString, $("#myForm"));