javascript - 在javascript中将复选框的属性值插入数组

标签 javascript arrays

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

<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"
    }
]

非常感谢

最佳答案

您可以字符串化您的数据并将其设置在隐藏框中。您可以解析并在任何您想要的地方使用。

$(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")
            });
            $("#arr").val(JSON.stringify(selected));
        });
        console.log(JSON.stringify(selected));
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="100400020719-006" name="selected" class="inforID" id="ABS-02072019" plant="VDNF" flowno="FLW-000001">

<input type="checkbox" value="100400020719-007" name="selected" class="inforID" id="ABS-02072018" plant="VDND" flowno="FLW-000002">

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

<input type="button" value="get" id="btnConf"/>

关于javascript - 在javascript中将复选框的属性值插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56863124/

相关文章:

javascript - 为什么非动态创建的 iframe 填充程序会显示,而动态创建的 iframe 填充程序则不会显示?

c# - ASP.Net MVC RouteData 和数组

javascript - 仅当 Promise 解析时才使用 JS Array.push

java - 数组的第一个值

c - 生命游戏 - 结构单元的二维数组,最好的结构方式是什么?

javascript - 当服务器宕机时,不会返回错误

javascript - 每个元素上的淡入淡出 - 滚动

javascript - $inc 追随者数量,还是我应该使用聚合来跟踪他们?

ios - 如何在特定索引处将数组插入现有NSMutableArray中

javascript - 不同条件下的 React 调用方法