Javascript 计数选中的复选框

标签 javascript checkbox checked

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

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

关于Javascript 计数选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11838667/

相关文章:

javascript - 在 jQuery 中查找并淡出一个元素

javascript - 复选框在映射函数中不起作用 react js css

html - 如何在 Weebly 中设置默认选中的单选按钮

javascript - jQuery 和 IE : Checking for hidden inputs "checked"-attribute does not work

javascript - 我如何使用 WebGL 创建基于 float 的 RGBA 纹理?

javascript - WebWorker - 传输包含对象的数组

javascript - 如何在 URI 中实现 Facebook 相册的影响?

javascript - 仅显示选中复选框的文本区域,未选中时隐藏

java - 我的复选框的名称无法解析

jquery - 如何根据是否仅使用 CSS 检查复选框来更改元素的不透明度?