jQuery 计算使用jquery检查的html复选框的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1957290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:27:59  来源:igfitidea点击:

calculate the number of html checkbox checked using jquery

jqueryhtmlformscheckbox

提问by bogha

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

我如何计算用户使用 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.

我想要做的是将表单中复选框的检查次数限制为 10,例如,当用户超出此范围时显示警告消息。

回答by Sarfraz

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

方法:3

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

回答by James Wiseman

This should work:

这应该有效:

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

回答by Richik SC

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.

如果上述方法均无效,则您可能还没有导入 jQuery。要导入 jQuery,请将此代码粘贴到<head>您的 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.

我在创建产品订购页面时实际上遇到了同样的问题,我希望它在订单确认页面计算购物车中的产品数量。我参考了这篇文章并尝试了所有方法。然后我发现我没有导入 jQuery,所以$(':checkbox:checked')没有用。

回答by rioted

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

.size()(当前接受的答案中的方法编号 1)自 jQuery 1.8 起已弃用