【发布时间】:2014-08-14 13:45:43
【问题描述】:
有复选框,属于Form A:
<input type="checkbox" class="item-selector" name="item[]" value="1" />
<input type="checkbox" class="item-selector" name="item[]" value="2" />
<input type="checkbox" class="item-selector" name="item[]" value="3" />
<!-- etc. -->
然后我有表单 B,它需要表单 A 中的复选框值。表单 A 可能也有其他输入字段,但我对这些不感兴趣。我只关心$('input.item-selector')。我是这样处理的:
var postData = $('#form-a').serializeArray();
var items = $('.item-selector:checked').map(function(){
return this.value;
}).get();
if(items.length > 0) {
postData.push({name: 'itemId', value: items});
}
但是这种向postData 添加内容的方式似乎不起作用,因为我发送表单的PHP 脚本找不到itemId。有趣的是,这确实有效:
postData.push(name: 'aName', value: 'notAnArrayButAStringValue');
我也尝试了几个像这样的解决方案:http://benalman.com/projects/jquery-misc-plugins/#serializeobject 但它们的问题是,虽然它们工作正常,但由于某种原因,如果表单 B 中有复选框,则表单 B 的复选框值被解析错误并导致空值和数据丢失。看起来像这样:
var postData = $(this.form).serializeObject();
var items = $('.item-selector:checked').map(function(){
return this.value;
}).get();
if(items.length > 0) {
postData.itemId = items;
}
使用 JSON.stringify 显示对象结构如下:
{
"name":"Simon J. Kok",
"address_id":"39669",
"email":"*****",
"content_id":"21921",
"client_id":"42101",
"is_ebill":["","1"], <-- this is a checked checkbox
"is_banned":"", <-- this is an unchecked checkbox
"button":"save"
}
Form B 中的复选框看起来像
<input type="checkbox" value="1" name="is_ebill" />
<input type="checkbox" value="1" name="is_banned" />
所以我需要了解如何将表单 A 中的复选框添加到 $.serializeArray() 结果数组 - 或者 - 一种解决使用 Ben Alman 插件时选中的复选框返回数组问题的方法。
【问题讨论】:
标签: javascript jquery arrays forms checkbox