bogha
bogha

Reputation: 551

calculate the number of html checkbox checked using jquery

how can i calculate the number of checkboxes that a user has checked using jquery?

what i want to do is limiting the number of checking for checkboxes in a form to 10 for example and when a user exceeds this range display a warning message.

Upvotes: 25

Views: 58287

Answers (4)

Sarfraz
Sarfraz

Reputation: 382776

There are multiple methods to do that:

Method 1:

alert($('.checkbox_class_here:checked').size());

Method 2:

alert($('input[name=checkbox_name]').attr('checked'));

Method: 3

alert($(":checkbox:checked").length);

Upvotes: 74

rioted
rioted

Reputation: 1092

you ought to use

alert($("input:checkbox:checked").length);

or

alert($(".checkbox-class:checked").length);

if you have more forms on one page

.size() (method number 1 in current accepted answer) is deprecated since jQuery 1.8

Upvotes: 0

Richik SC
Richik SC

Reputation: 884

If none of the methods above work, you probably haven't imported jQuery yet. To import jQuery, paste this code into the <head> of your HTML.

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

I actually had the same problem while creating a product ordering page, and I wanted it to count The number of products in the cart at the order confirmation page. I referred to this post and tried all of the methods. Then I found out I did not import jQuery, so the $(':checkbox:checked') did not work.

Upvotes: 2

Mutation Person
Mutation Person

Reputation: 30500

This should work:

alert($("input:checkbox:checked").length);

Upvotes: 18

Related Questions