选中Javascript计数复选框 [英] Javascript count checked checkbox

查看:233
本文介绍了选中Javascript计数复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可能有一些类似的问题@stackoverflow,但我没有找到任何解决我的问题:

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...

number as idVideo..thats the point。

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

额外的细节:
form name = 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++;

To:

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/

em>全部输入,检查每个输入的类型(和/或名称):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆