我有一个相当复杂的表格,其中包含许多“步骤”,这些步骤由用户填写。某些步骤(将它们视为表单段)具有默认选项,但是在单击“输入自定义值”时,它们会显示一个此处隐藏的字段集,用户可以在其中输入信息。这是一个示例
<div id="#s1_normal">
<input type="radio" name="mode" value="a"> Mode A
<input type="radio" name="mode" value="b"> Mode B
Choose one of the above for applying average coefficient
values of "a" or "b" to 100% of your product or
<a href="#" onclick="toggleCustom('s1');">enter custom values</a>
</div>
<div id="#s1_custom">
%a: <input type="text" name="perc_a"> coeff. a <input type="text" name="coeff_a">
%b: <input type="text" name="perc_b"> coeff. b <input type="text" name="coeff_b">
Enter custom values above or
<a href="#" onclick="toggleCustom('s1');">choose average values</a>
有几个这样的段,例如#s1 ..#s7。这是我的任务。我想使用户能够保存表单的状态。因此,一旦用户填写了整个表单,为某些段选择了平均默认值,并为其他段输入了自定义值,则用户可以单击按钮并保存整个状态以供以后解冻。我在想,如果我可以将状态保存在可以序列化的对象中,则可以将其保存在db表或其他持久存储中。
用户可以稍后再回来,并重新构建整个先前的会话。
我该怎么做呢?有getAttributes插件http://plugins.jquery.com/project/getAttributes,还有jQuery serialize方法,但是我一生都无法入门。请按正确的方向轻推我。
最佳答案
这里有几个函数可以帮助完成此过程。 formToString
将表单序列化为字符串,而stringToForm
则相反:
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]);
}
}
});
}
用法:
// Convert form to string
var formString = formToString($("#myForm"));
// Save string somewhere, e.g. localStorage
// ...
// Restore form from string
stringToForm(formString, $("#myForm"));