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.
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.
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);
This should work:
alert($("input:checkbox:checked").length);
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.
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