Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何循环检查复选框并添加到数组_Javascript_Jquery_Arrays - Fatal编程技术网

Javascript 如何循环检查复选框并添加到数组

Javascript 如何循环检查复选框并添加到数组,javascript,jquery,arrays,Javascript,Jquery,Arrays,我需要遍历特定名称的所有复选框,并将该行的值添加到数组中。我的最终阵列需要如下所示: stmtData = { sections: [ { sectionCode: "AA", sectionName: "AA Test", amount: "33" }, { sectionCode: "BB", sectionName: "BB Test", amount: "55" } ] }; 在复选框上循环是最简单的部分: var stmtData =

我需要遍历特定名称的所有复选框,并将该行的值添加到数组中。我的最终阵列需要如下所示:

stmtData = {
    sections: [
        { sectionCode: "AA", sectionName: "AA Test", amount: "33" },
        { sectionCode: "BB", sectionName: "BB Test", amount: "55" }
    ]
};
在复选框上循环是最简单的部分:

var stmtData = [];
$.each($("input:checkbox[name='sectionElection']:checked"), function () {
    // create sections array here

});
我得到的数据是这样的,但有更好的方法吗

stmtData["sectionCode"] = $(this).val();
stmtData["sectionName"] = $("#sectionElectionLbl_" + $(this).val()).text();
stmtData["amount"] = $("#sectionCost_" + $(this).val()).text();

您可以使用map来改进它,而不是使用jQuery上的每一个,但类似于

var stmtData = {}
stmtData.section = $("input:checkbox[name='sectionElection']:checked")
.map(function() {

  var val = $(this).val();
  var text = val.text();
  return {
        sectionCode: val,
        sectionName = $("#sectionElectionLbl_" + text,
        amount: text
    }
});

您可以使用map来改进它,而不是使用jQuery上的每一个,但类似于

var stmtData = {}
stmtData.section = $("input:checkbox[name='sectionElection']:checked")
.map(function() {

  var val = $(this).val();
  var text = val.text();
  return {
        sectionCode: val,
        sectionName = $("#sectionElectionLbl_" + text,
        amount: text
    }
});

好吧,我知道我必须用推的方式,我想出来了,这一切都很好

var stmtData = [];
$.each($("input:checkbox[name='sectionElection']:checked"), function () {
    // create sections array here
    stmtData.push({
        sectionCode: $(this).val(),
        sectionName: $("#sectionElectionLbl_" + $(this).val()).text(),
        amount: $("#sectionCost_" + $(this).val()).text()
    });
});

好吧,我知道我必须用推的方式,我想出来了,这一切都很好

var stmtData = [];
$.each($("input:checkbox[name='sectionElection']:checked"), function () {
    // create sections array here
    stmtData.push({
        sectionCode: $(this).val(),
        sectionName: $("#sectionElectionLbl_" + $(this).val()).text(),
        amount: $("#sectionCost_" + $(this).val()).text()
    });
});