javascript 如何将复选框中的值添加到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7400325/
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
How to add the values from checkboxes to an array
提问by user1946705
I have a form that contains a couple of checkboxes. After send this form I would need these checkboxes (the values) to a javascript array.
我有一个包含几个复选框的表单。发送此表单后,我需要将这些复选框(值)添加到 javascript 数组中。
Could anyone give me a favor, please, how to do?
谁能帮我一个忙,怎么办?
回答by user278064
var form = document.getElementById("yourformname"),
inputs = form.getElementsByTagName("input"),
arr = [];
for (var i = 0, max = inputs.length; i < max; i += 1) {
// Take only those inputs which are checkbox
if (inputs[i].type === "checkbox" && inputs[i].checked) {
arr.push(inputs[i].value);
}
}
回答by totallyNotLizards
with jquery you could do something like this:
使用 jquery,您可以执行以下操作:
var checkboxArr=[];
$('input[type=checkbox]').each(function(){
checkboxArr.push(this);
});
Untested and not sure how this would work in pure js, maybe it can point you in the right direction
未经测试,不确定这在纯 js 中如何工作,也许它可以为您指明正确的方向
回答by Dennis
var values = [],
inputs = document.getElementsByTagName("input");
for (var i = inputs.length -1 ; i>= 0; i--)
if (inputs[i].type === "checkbox" && inputs[i].checked)
values.push(inputs[i].value);
for pure JS.
对于纯 JS。
回答by Jiri Kriz
You can test the following function on jsfiddle:
您可以在jsfiddle上测试以下功能:
function getCheckboxes(form_id, name) {
// returns array of checked checkboxes with 'name' in 'form_id'
var form = document.getElementById(form_id);
var inputs = form.getElementsByTagName("input");
var values = [];
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type === "checkbox" &&
inputs[i].name === name &&
inputs[i].checked)
{
values.push(inputs[i].value);
}
}
return values;
}