jQuery jquery多个复选框数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6166763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery multiple checkboxes array
提问by user557108
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
How I can make an array with values of checkboxes that are checked?
如何使用选中的复选框的值创建数组?
NOTE: (IMPORTANT) I need an array like [1, 2, 3, 4, 5] and not like ["1", "2", "3", "4", "5"] .
NOTE: There are around 50 checkboxes.
注意:(重要)我需要一个像 [1, 2, 3, 4, 5] 而不是像 ["1", "2", "3", "4", "5"] 的数组。
注意:大约有 50 个复选框。
Can someone help me? Please!
有人能帮我吗?请!
Thank you!
谢谢!
回答by Dormouse
var checked = []
$("input[name='options[]']:checked").each(function ()
{
checked.push(parseInt($(this).val()));
});
回答by Russ Cam
You can use $.map()
(or even the .map()
function that operates on a jQuery object) to get an array of checked values. The unary (+) operator will cast the string to a number
您可以使用$.map()
(甚至.map()
是对 jQuery 对象进行操作的函数)来获取一组检查值。一元 (+) 运算符将字符串转换为数字
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
console.log(arr);
Here's an example
这是一个例子
回答by user2503922
var checkedString = $('input:checkbox:checked.name').map(function() { return this.value; }).get().join();
回答by Muhammad Amjad
If you have a class for each of your input box, then you can do it as
如果你的每个输入框都有一个类,那么你可以这样做
var checked = []
$('input.Booking').each(function ()
{
checked.push($(this).val());
});
回答by Hasan Shouman
A global function that can be reused:
一个可以重用的全局函数:
function getCheckedGroupBoxes(groupName) {
var checkedAry= [];
$.each($("input[name='" + groupName + "']:checked"), function () {
checkedAry.push($(this).attr("id"));
});
return checkedAry;
}
where the groupName is the name of the group of the checkboxes, in you example :'options[]'
其中 groupName 是复选框组的名称,例如:'options[]'
回答by Pedro Trujillo
This way will let you add or remove values when you check or uncheck any checkbox named as options[]
:
当您选中或取消选中任何名为 的复选框时,这种方式将允许您添加或删除值options[]
:
var checkedValues = [];
$("input[name='options[]']").change(function() {
const intValue = parseInt($(this).val());
if ($(this).is(':checked')) {
checkedValues.push(value);
} else {
const index = checkedValues.indexOf(value);
if (index > -1) {
checkedValues.splice(index, 1);
}
}
});