使用 javascript 循环检查复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23307829/
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
Looping through checkboxes with javascript
提问by Nick Law
I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server to saved in a table. I have tried the below code:
我有许多复选框,我想检查它们是被选中 (1) 还是未选中 (0)。我想将结果放在一个数组中,以便我可以将它们发送到服务器以保存在表中。我试过下面的代码:
<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>
<script>
$('#save-btn').click(function(evt){
evt.preventDefault();
var numberOfChBox = $('.publish').length;
var checkArray = new Array();
for(i = 1; i <= numberOfChBox; i++) {
if($('#chkBox' + i).is(':checked')) {
checkArray[i] = 1;
} else {
checkArray[i] = 0;
}
}
alert(checkArray);
});
</script>
but the alert outputs this:
但警报输出:
,1,0,1,0,1,1
The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?
除了 undefined 中的第一个索引外,这些值都是正确的。总共只有 5 个复选框,但数组有 6 个索引长。为什么是这样?
回答by Tats_innit
Try this efficient way bruvo :)
http://jsfiddle.net/v4dxu/with proper end tag in html: http://jsfiddle.net/L4p5r/
尝试这种有效的方式 bruvo :)
http://jsfiddle.net/v4dxu/在 html 中使用适当的结束标记:http: //jsfiddle.net/L4p5r/
Pretty good link: https://learn.jquery.com/javascript-101/arrays/
很好的链接:https: //learn.jquery.com/javascript-101/arrays/
Also in your html end your tag />
i.e.
同样在你的 html 结束你的标签/>
即
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
rest should help :)
休息应该有帮助 :)
Code
代码
var checkArray = new Array();
$('input[type=checkbox]').each(function () {
this.checked ? checkArray.push("1") : checkArray.push("0");
});
alert(checkArray);
回答by Alfonso Jiménez
Take into account that the first element you write is checkArray[1]
, as i
starts with 1
, instead of checkArray[0]
.
考虑到你写的第一个元素是checkArray[1]
,作为i
与开始1
,而不是checkArray[0]
。
Replace checkArray[i]
with checkArray[i-1]
inside the for bucle
替换checkArray[i]
为checkArray[i-1]
内部 for bucle
回答by Selvaraj M A
As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?
正如上面的答案中提到的,问题出在索引(i)上。但是如果你想进一步简化代码,下面的代码怎么样?
var checkArray = [];
$('input.publish').each(function () {
checkArray.push($(this).is(':checked'));
});
alert(checkArray);