Get number of checkboxes that are checked in Javascript

北慕城南 提交于 2019-12-17 20:06:30

问题


I am trying to make a javascript function (although jquery is perfectly OK) that will return a number that corresponds to the number of checkboxes checked in a form. Seems simple enough but I can't figure out a good way of doing it.

Thanks.


回答1:


Try this:

var formobj = document.forms[0];

var counter = 0;
for (var j = 0; j < formobj.elements.length; j++)
{
    if (formobj.elements[j].type == "checkbox")
    {
        if (formobj.elements[j].checked)
        {
            counter++;
        }
    }       
}

alert('Total Checked = ' + counter);

.

With JQuery:

alert($('form input[type=checkbox]:checked').size());



回答2:


$('form :checkbox:checked').length




回答3:


 var checkBoxs = $('#myForm').children('input[type="checkbox"]:checked');
 alert(checkBoxs.length);



回答4:


var chk = $('form').find('input[type=checkbox]:checked').length



回答5:


Try

$(":checkbox").filter(":checked").size()



回答6:


vary long way

you have to give the class name to checkbox and do

var chkLength = $('input.className:checked').length;

alert(chkLength);

this will gove all checked checkBoxes from list of checkbox



来源:https://stackoverflow.com/questions/2697329/get-number-of-checkboxes-that-are-checked-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!