calculate the number of html checkbox checked usin

2020-01-25 09:38发布

问题:

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.

回答1:

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);


回答2:

This should work:

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


回答3:

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.



回答4:

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