我知道@stackoverflow 可能有一些类似的问题,但我还没有找到解决我的问题的方法: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 的数量相同..这就是重点。
现在,在提交之前,我需要确保至少选中了一个复选框。但是我没有成功 :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"
你能指导我一下吗? 谢谢
编辑:
function isCountCheck(){
if($("input[type=checkbox]:checked").length > 0)
{
return true;
}
else
{
alert('Invalid');
return false;
}
}
但仍然无法正常工作..即使显示了该警报..
最佳答案
主要问题是您没有在循环中使用 i
索引来引用各个复选框,并且您有一个 .
就在 [
这是一个语法错误。所以改变:
if(document.form1.["checkbox-1[]"].checked) chkCnt++;
收件人:
if(document.form1["checkbox-1[]"][i].checked) chkCnt++;
但是您可以按如下方式稍微整理一下函数:
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/
或者只是遍历表单中的所有输入,检查每个输入的类型(和/或名称):
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;
}
关于Javascript 计数选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11838667/