首页 > 解决方案 > 在javascript中将复选框的属性值插入数组

问题描述

我的表单中有多个复选框,其值如下

<input type="checkbox" value="100400020719-006" name="selected" class="inforID" id="ABS-02072019" plant="VDNF" flowno="FLW-000001">

选中复选框并按下按钮时,我将获取属性并插入带有 id 的输入arr

<input type="hidden" id="arr" name="arr" /> 

$(document).ready(function() {
    $("#btnConf").click(function(){
        var selected = [];
        $.each($("input[name='selected']:checked"), function () {
            selected.push($(this).val(), $(this).attr("id"), $(this).attr("plant"), $(this).attr("flowno"));
            document.getElementById("arr").value = selected;
        });
        console.log(selected);
    });
});

但我得到的数组是

<input type="hidden" id="arr" name="arr" value="100400020719-006,ABS-02072019,VDNF,FLW-000001,100400020719-007,ABS-02072019,VDNF,FLW-000001">

我怎样才能得到这样的数组:

[
    {
        "DocNo":"100400020719-006",
        "NewDocNo":"ABS-02072019",
        "Plant":"VDNF",
        "FlowNow":"FLW-000001"
    },
    {
        "DocNo":"100400020719-007",
        "NewDocNo":"ABS-02072019",
        "Plant":"VDNF",
        "FlowNow":"FLW-000001"
    }
]

或者像这样

[
    {
        "100400020719-006",
        "ABS-02072019",
        "VDNF",
        "FLW-000001"
    },
    {
        "100400020719-007",
        "ABS-02072019",
        "VDNF",
        "FLW-000001"
    }
]

非常感谢

标签: javascriptarrays

解决方案


将选中的复选框属性值作为JS 对象插入到selected 数组 中

$(document).ready(function() {
  $("#btnConf").click(function() {
    var selected = [];
    $.each($("input[name='selected']:checked"), function() {
      selected.push({
        "DocNo": $(this).val(),
        "NewDocNo": $(this).attr("id"),
        "Plant": $(this).attr("plant"),
        "FlowNow": $(this).attr("flowno")
      });
      document.getElementById("arr").value = selected;
    });
    console.log(selected);
  });
});


推荐阅读