使用javascript循环浏览复选框 [英] Looping through checkboxes with javascript
问题描述
我有一些复选框,我想检查它们是否被选中(1)或未选中(0)。我想将结果放在数组中,以便我可以将它们发送到服务器以保存在表中。我试过了下面的代码:
< input class =publishid =chkBox1type =checkboxchecked> ;
< input class =publishid =chkBox2type =checkboxchecked>
< input class =publishid =chkBox3type =checkboxchecked>
< input class =publishid =chkBox4type =checkboxchecked>
< input class =publishid =chkBox5type =checkboxchecked>
< script>
$('#save-btn')。click(function(evt){
evt.preventDefault();
var numberOfChBox = $('。publish')。 ($($ = $; $ i $);
var checkArray = new Array();
$ b $ for(i = 1; i <= numberOfChBox; i ++){
if #chkBox'+ i).is(':checked')){
checkArray [i] = 1;
} else {
checkArray [i] = 0;
}
}
alert(checkArray);
});
< / script>
但警报输出:
,1,0,1,0,1,1
除了第一个未定义的索引之外,这些值是正确的。总共只有5个复选框,但数组长度为6个索引。为什么会这样?
考虑到您写的第一个元素是 checkArray [1]
,作为 i
以 1
开头,而不是 checkArray [0 ]
。
将
checkArray [i]
替换为 checkArray [i-1]
在forclecle 中
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:
<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?
Take into account that the first element you write is checkArray[1]
, as i
starts with 1
, instead of checkArray[0]
.
Replace checkArray[i]
with checkArray[i-1]
inside the for bucle
这篇关于使用javascript循环浏览复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!