我的问题是如何通过searilizedarray()在一个数组中一起序列化复选框值和文本框值...

现在我得到这样的东西

       [{"name":"text_input","value":"kalpit"},
        {"name":"wpc_chkbox[]","value":"Option one"},
        {"name":"wpc_chkbox[]","value":"Option two"},
        {"name":"wpc_chkboxasdf[]","value":"Option one"},
       {"name":"wpc_chkboxasdf[]","value":"Option two"},
       {"name":"wpc_inline_chkbox[]","value":"1"},
       {"name":"wpc_inline_chkbox[]","value":"2"},
       {"name":"wpc_inline_chkbox[]","value":"3"},
       {"name":"wpc_radios","value":"Option one"}]


但它应该像

     [{"name":"text_input","value":"kalpit"},
        {"name":"wpc_chkbox[]","value":"[Option one,Option Two]"},
        {"name":"wpc_chkboxasdf[]","value":"[Option one,Option Two]"},
       {"name":"wpc_inline_chkbox[]","value":"[1,2,3]"},
       {"name":"wpc_radios","value":"Option one"}]


我正在使用var form = $('.wpc_contact').serializeArray();获取表单数据

这是我使用拖放未来动态生成的HTML示例。

  <form method="POST" name="1" class="form-horizontal wpc_contact" novalidate="novalidate">
   <fieldset>
     <div id="legend" class="">
       <legend class="">Demo</legend>
       <div id="alert-message" class="alert hidden" style="color: red;"></div>
     </div>

<div class="control-group">
    <label class="control-label">Checkboxes</label>
    <div class="controls" name="wpc_chkbox" req="yes">
            <input type="checkbox" value="Option one" id="wpc_chkbox_0" name="wpc_chkbox[]" req="yes">  Option one
            <input type="checkbox" value="Option two" id="wpc_chkbox_1" name="wpc_chkbox[]" req="yes">   Option two
    </div>
</div>
<div class="control-group">
    <div class="controls" name="wpc_inline_chkbox" req="yes">
            <input type="checkbox" value="1" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_0" req="yes"> 1
            <input type="checkbox" value="2" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_1" req="yes"> 2
            <input type="checkbox" value="3" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_2" req="yes"> 3
    </div>
</div>

<div class="control-group">
    <div class="controls">
        <button class="btn btn-success">Button</button>
    </div>
</div>
</fieldset>
</form>


提前致谢

最佳答案

尝试这个:

   var cacheObject = {};//tmp cache for form elements name/values pairs
    var serArr = $('.wpc_contact').serializeArray();

    //set values of elements to cacheObject
    $.each(serArr, function (arrayIndex,obj) {
        if (cacheObject[obj.name]) {
            cacheObject[obj.name].push(obj.value);
        } else {
            cacheObject[obj.name] = [obj.value];
        }
    });

    //create new serialized array
    var newSerArr = [];
    $.each(cacheObject, function (key, value) {
        var obj = {};
        obj[key] = value;
        newSerArr.push(obj);
    });

    console.log(newSerArr);//looks like serializeArray

10-06 11:57