繁体   English   中英

将选中的复选框值及其名称存储在二维数组中

[英]Store the checked checkbox value and it's name in a two dimensional array

我想将选中的复选框值及其名称存储在二维数组中,这是html代码。

<h3>Select your favorite sports:</h3>
<label>
    <input type="checkbox" value="football" name="football"> Football</label>
<label>
    <input type="checkbox" value="baseball" name="baseball"> Baseball</label>

而且我只能显示选中的检查框值,这是jQuery代码

$(document).ready(function () {
    $("button").click(function () {
        var favorite = [];
        $.each($("input:checked"), function () {
            favorite.push($(this).val());
        });
        alert("My favourite sports are: " + favorite);
    });
});

我的问题是如何将两个值和它的名称存储在“最喜欢的数组”中?

您可以为此使用对象数组

favorite.push({
   name: $(this).attr('name'),
   value:$(this).val()
});

实际观看

输出:

[{
    "name": "football",
    "value": "football"
}, {
    "name": "baseball",
    "value": "baseball"
}]

如果要显示值:

$.each(favorite, function(index, obj){
   console.log("Name= "+ obj.name+"  Value="+ obj.value);
})

使用map()转换数组或对象中的所有项目

var favorite= $("input:checked").map(function () {
    var obj = {};
    obj[$(this).attr('name')] = this.value;
    return obj;

}).get();

console.log(favorite)

DEMO

使用对象数组

$(document).ready(function () {
    $("button").click(function () {
        var favorite = [];
        $.each($("input:checked"), function () {

            // Add object in array
            favorite.push({
                name: $(this).attr('name'),
                value: $(this).val()
            });
        });
        console.log("My favourite sports are: ");
        console.log(favorite);
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM