Javascript count checked checkbox

旧时模样 提交于 2019-11-28 13:55:05

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

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

Demo: http://jsfiddle.net/nnnnnn/ZjK3w/2/

Simplest solution:

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

No need for jQuery. Supported down to IE8. use polyfill for older browsers if you wish.

Use Jquery:

function isCountCheck(helperMsg){
    if($("input[type=checkbox]:checked").length > 0)
        return true;
    alert(helperMsg);
    return false;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!