Javascript 计数选中复选框 [英] Javascript count checked checkbox
问题描述
我知道@stackoverflow 可能有一些类似的问题,但我还没有找到任何解决我的问题的方法 :s
I know that may have a few similar questions @stackoverflow, but I didnt found any solution to my problem yet :s
<?php
while($rowVideo = mysql_fetch_array($ResultQueryVideo))
{
?>
<input type="checkbox" name = "checkbox-1[]" class="checkbox" value ="<?php echo $rowVideo['idVideo'] ?>" /> <?php....some code...
这会产生几个复选框,与 idVideo 的数字相同..这就是重点.
This results a few checkbox's, the same number as idVideo..thats the point.
现在,在提交之前,我需要确保至少选中了一个复选框.但我没有成功 :x
Now, before the submit, I need to be sure that at least one checkbox is checked. But i was not sucesseful :x
function isCountCheck (helperMsg) {
var chkCnt = 0;
var Frm = document.forms[0];
var dLen = Frm.length - 1;
for (i=0;i<=dLen;i++) {
if(document.form1.["checkbox-1[]"].checked) chkCnt++;
}
if (chkCnt>0) {
return true;
} else {
alert(helperMsg);
return false;
}
}
额外的细节:表单名称 = "form1"
Extra details: form name = "form1"
你能指导我一下吗?谢谢
Can you guide me a litle ? Thanks
function isCountCheck(){
if($("input[type=checkbox]:checked").length > 0)
{
return true;
}
else
{
alert('Invalid');
return false;
}
}
但仍然无法正常工作..即使显示该警报..
But still not working..even that alert is shown..
推荐答案
主要问题是您没有在循环中使用 i
索引来引用各个复选框,并且您已经在 [
之前得到了一个 .
,这是一个语法错误.所以改变:
The main problem is that you're not using the i
index within the loop to reference the individual checkboxes, and you've got a .
just before the [
which is a syntax error. So change:
if(document.form1.["checkbox-1[]"].checked) chkCnt++;
致:
if(document.form1["checkbox-1[]"][i].checked) chkCnt++;
但是你可以稍微整理一下函数如下:
But you can neaten up the function somewhat as follows:
function isCountCheck(helperMsg) {
var i, dLen = document.form1["checkbox-1[]"].length;
// if the length property is undefined there is only one checkbox
if (typeof dLen === "undefined") {
if (document.form1["checkbox-1[]"].checked) return true;
}
else {
for (i = 0; i < dLen; i++) {
if (document.form1["checkbox-1[]"][i].checked) return true;
}
}
alert(helperMsg);
return false;
}
演示:http://jsfiddle.net/nnnnnn/ZjK3w/1/
或者只是遍历表单中的所有输入,检查每个输入的类型(和/或名称):
Or just loop through all inputs in the form, checking the type (and/or the name) of each one:
function isCountCheck(helperMsg) {
var i, len, inputs = document.form1.getElementsByTagName("input");
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox"
&& inputs[i].checked)
return true;
}
alert(helperMsg);
return false;
}
演示:http://jsfiddle.net/nnnnnn/ZjK3w/2/
这篇关于Javascript 计数选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!