我有多个表单,我正在处理表单的序列化数组。
期望:
所以在下面的代码中我创建了一个临时对象tmpObj
,我试图将所有迭代的表单值推送到tmpObj下的字段中。
tmpObj有多个属性,如字段1和字段2,它具有firstname和lastname等属性。
我需要将此tmpObj推送到items
数组。
我的表单有firstname和lastname,我需要迭代这个表单并获取firstname和lastname的值,我需要将它推送到对象,并且对象应该被推送到items数组。
但是如果我正在执行序列化数组,那么只能在firstname字段中推送firstname或lastname。
预期产出:
{
"items": [
{
"fieldset": {
"field1": {
"firstName": "abc",
"lastName": "def"
}
},
"field2": {
"firstName": "abc",
"lastName": "def"
}
},
{
"fieldset": {
"field1": {
"firstName": "ghi",
"lastName": "jkl"
}
},
"field2": {
"firstName": "ghi",
"lastName": "jkl"
}
}
]
}
这就是我的尝试:
HTML:
<form id="f1" class="forms">
<div class="f-grp">
<label for ="fn1">First Name</label>
<input type="text" name="fn1" id="fn1" />
</div>
<div class="f-grp">
<label for ="ln1">First Name</label>
<input type="text" name="ln1" id="ln1" />
</div>
</form>
<form id="f2" class="forms">
<div class="f-grp">
<label for ="fn2">First Name</label>
<input type="text" name="fn2" id="fn2" />
</div>
<div class="f-grp">
<label for ="ln2">Last Name</label>
<input type="text" name="ln2" id="ln2" />
</div>
</form>
<button type="submit" id="submit">Submit</button>
JS:
$(document).ready(function(){
$('#submit').click(function(){
setFormObj();
});
});
var setFormObj = function(){
var self = this;
self.myObj = {};
myObj.items = [];
self.tmpObj = {
fieldset: {
field1: {
firstName: "",
lastName: ""
}
},
field2: {
firstName: "",
lastName: ""
}
};
$('.forms').each(function(fKey, fValue){
var _serArr = $(this).serializeArray();
$(_serArr).each(function(sKey, sValue){
var value = sValue.value;
tmpObj.transferOldNumberInfo.addressfields.firstName = value;
});
});
}