[英]Store the checked checkbox value and it's name in a two dimensional array
I want to store the checked checkbox value and it's name in a two dimensional array, here is html code. 我想将选中的复选框值及其名称存储在二维数组中,这是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>
And I can only display the checked checbox values, here is jQuery code 而且我只能显示选中的检查框值,这是jQuery代码
$(document).ready(function () {
$("button").click(function () {
var favorite = [];
$.each($("input:checked"), function () {
favorite.push($(this).val());
});
alert("My favourite sports are: " + favorite);
});
});
My question is how to store both values and It's name in favorite array? 我的问题是如何将两个值和它的名称存储在“最喜欢的数组”中?
You can use Array of objects for this: 您可以为此使用对象数组 :
favorite.push({
name: $(this).attr('name'),
value:$(this).val()
});
Output: 输出:
[{
"name": "football",
"value": "football"
}, {
"name": "baseball",
"value": "baseball"
}]
If you want to display values: 如果要显示值:
$.each(favorite, function(index, obj){
console.log("Name= "+ obj.name+" Value="+ obj.value);
})
Use array of objects 使用对象数组
$(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.