9

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.

6 Answers 6

16

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());
Sign up to request clarification or add additional context in comments.

3 Comments

Just for clarification - the standard JS code will not pick up input elements that are not inside a form. The jQuery line will.
@danp: yes now both ways will select all checkboxes from a form.
With the JQuery, like $('form input[type=checkbox]:checked'), how to get the details about the id of item that is checked?
4

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

2 Comments

Whats the difference between .length and .size()?
4
 var checkBoxs = $('#myForm').children('input[type="checkbox"]:checked');
 alert(checkBoxs.length);

Comments

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

Comments

1

Try

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

1 Comment

@Yuriy Faktorovich: Just for illustration. I have now removed it @Sarfraz: You are right. I've corrected it
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.