我如何计算使用 jQuery 在页面上选择了多少个复选框 [英] How do I count how many checkboxes are selected on a page with jQuery

查看:12
本文介绍了我如何计算使用 jQuery 在页面上选择了多少个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算我的页面上有多少复选框是使用 jQuery 选中的.我编写了以下代码:

I want to count how many checkboxes on my page are selected using jQuery. I've written the following code:

      var numberOfCheckboxesSelected = 0;
      $(':checkbox').each(function(checkbox) {
          if (checkbox.attr('checked'))
              numberOfCheckboxesSelected++;
      });

但是,我的代码在第三行出现错误消息对象不支持此属性或方法".

However, my code errors out with the message "Object doesn't support this property or method" on the third line.

如何计算我的页面上选中了多少个复选框?

How do I count how many checkboxes are selected on my page?

推荐答案

jQuery 支持 :checked 伪选择器.

jQuery supports the :checked pseudo-selector.

var n = $("input:checked").length;

这适用于单选按钮和复选框.如果您只想要复选框,而且页面上还有单选按钮:

This will work for radio buttons as well as checkboxes. If you just want checkboxes, but also have radio buttons on the page:

var n = $("input:checkbox:checked").length;

这篇关于我如何计算使用 jQuery 在页面上选择了多少个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆