pun*_*ish 19 forms jquery session-state
我有一个相当复杂的形式,其中有许多"步骤",由用户填写.某些步骤(将它们视为表单段)具有默认选项,但在单击"输入自定义值"时,它们会显示一个隐藏的字段集,用户可以在其中输入信息.这是一个示例
<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>
Run Code Online (Sandbox Code Playgroud)
有几个这样的段,例如,#s1 ..#s7.这是我的任务.我想让用户保存表单的状态.因此,一旦用户填写了整个表单,选择某些段的平均默认值,并为其他段输入自定义值,用户就可以单击一个按钮并保存整个状态以便稍后解冻.我在想,如果我可以将状态保存在我可以序列化的对象中,我可以将它保存在db表或其他持久存储中.
用户可以稍后返回并重新构建整个上一个会话.
我该怎么做呢?有getAttributes插件http://plugins.jquery.com/project/getAttributes,并且有jQuery serialize方法,但我不能为我的生活开始.请朝正确的方向推动我.
rwi*_*n04 23
以下是一些有助于此过程的功能.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]);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
用法:
// Convert form to string
var formString = formToString($("#myForm"));
// Save string somewhere, e.g. localStorage
// ...
// Restore form from string
stringToForm(formString, $("#myForm"));
Run Code Online (Sandbox Code Playgroud)
我猜您正在寻找.serialize(),它可以序列化form data
. 为此,您的input
元素需要在form tag
加号范围内,所有元素都必须具有name
属性。
var form1data = $('#form1').serialize();
alert(form1data);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16474 次 |
最近记录: |