选中 Javascript 计数复选框

Javascript count checked checkbox

本文关键字:复选框 Javascript 选中      更新时间:2023-09-26

我知道@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;
    }
}

额外详情:表单名称 ="表单 1"

你能指导我一点吗?谢谢

编辑:

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;
}

演示:http://jsfiddle.net/nnnnnn/ZjK3w/2/

最简单的解决方案:

var form = document.forms[0]; // your form element (whatever)
var checkedElms = form.querySelectorAll(':checked').length;

不需要 jQuery。支持低至 IE8。如果您愿意,可以对较旧的浏览器使用 polyfill。

使用 Jquery:

function isCountCheck(helperMsg){
    if($("input[type=checkbox]:checked").length > 0)
        return true;
    alert(helperMsg);
    return false;
}