Aditya P Bhatt
Aditya P Bhatt

Reputation: 22071

Javascript: get total checked checkboxes

I have a form and want to find, how many checkboxes have been checked?

My Checkbox id will be same, event_id and name will be something like this: data[Noncompetitor][is_black][4]

How can i?

Let me know ASAP.

Thanks !

Upvotes: 2

Views: 4135

Answers (2)

Anish
Anish

Reputation: 2917

You can use the below code to get the number of check box checked.

<html>
    <head>
        <script type="text/javascript">
        var index = 0;
        function check()
        {
            index++;
            document.getElementById('text').innerHTML = "You have Checked \t"+index+"\t checkboxes";
        }
        </script>
    </head>
    <body>
    <input type="checkbox" onclick="check()"/>
    <input type="checkbox" onclick="check()"/>
    <input type="checkbox" onclick="check()"/>
    <input type="checkbox" onclick="check()"/>
    <input type="checkbox" onclick="check()"/>
    <input type="checkbox" onclick="check()"/>
    <div id="text"></div>
    </body>
    </html>

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1074158

Once you have a reference to your form's element, it's easy to loop through the elements:

function countChecked(form) {
    var index, element;
    for (index = 0; index < form.elements.length; ++index) {
        element = form.elements[index];
        // You may want to check `element.name` here as well
        if (element.type.toUpperCase() == "CHECKBOX" && element.checked) {
            ++checked;
        }
    }
    return checked;
}

There are lots of ways to get a reference to the form element. For instance, give the form an id and use document.getElementById.

So if your form's id is "foo", for instance, then:

var checkedCount = countChecked(document.getElementById('foo'));

Off-topic: A lot of this stuff can be made a lot easier using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over browser differences, give you rich ways to traverse to elements via CSS selectors, and such.

For example, the above can be written using jQuery like this:

var checkedCount = $("#foo :checkbox:checked").length;

...which says, 'find all checked checkboxes that are descendants of the elemen twith the id "foo"' and then uses the length of the resulting jQuery object (jQuery objects are array-like).

Upvotes: 5

Related Questions