【问题标题】:Adding an array value to an array retrieved using $.serializeArray()将数组值添加到使用 $.serializeArray() 检索的数组中
【发布时间】: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


    【解决方案1】:

    这是一种方法。首先它需要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/

    【讨论】:

      【解决方案2】:

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

      var items = $('.item-selector:checked').map(function(){
          return this.value;
      }).get();
      
      $.each(items, function(i, v){
          postData.push({name: 'itemId[]', value: v});
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-02
        • 2023-03-08
        • 1970-01-01
        • 2012-02-24
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        • 2021-06-28
        相关资源
        最近更新 更多