将数组值添加到使用$ .serializeArray()检索的数组

时间:2014-08-14 13:45:44

标签: javascript jquery arrays forms checkbox

有复选框,属于表格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"
}

表格B中的复选框看起来像

<input type="checkbox" value="1" name="is_ebill" />
<input type="checkbox" value="1" name="is_banned" />

所以我需要的是有关如何将表单A中的复选框添加到$.serializeArray()结果数组的一些见解 - 或者 - 一种解决使用Ben Alman时返回数组的已选中复选框问题的方法&# 39; s插件。

2 个答案:

答案 0 :(得分:0)

这是一种方法。首先,它需要form-b中的隐藏字段:

<input type="hidden" id="itemId" name="itemId" value="" />

提交表单时,这将填充item-selector数据:

$('#form-b').on('submit', function() {
    var checkedValues = [];
    $('.item-selector:checked').each(function() {
        checkedValues.push($(this).val());
    });

    $('#itemId').val(checkedValues.join(','));
    console.debug('Form B data:', $('#form-b').serializeArray());
});

调整语法以适合您的习语。这是一个小提琴演示:

http://jsfiddle.net/klenwell/12evxfvc/

答案 1 :(得分:0)

实际上,当我问起时,我已经回答了我自己的问题。我使用JSON.Stringify输出JSON格式的字符串,其中包含$.serializeArray()返回的字符串,并且显然需要工作的结构。所以这里是如何逐个添加数组值到使用$.serializeArray()检索的数组:

var items = $('.item-selector:checked').map(function(){
    return this.value;
}).get();

$.each(items, function(i, v){
    postData.push({name: 'itemId[]', value: v});
});