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

查看:174
本文介绍了如何计算一个页面上用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天全站免登陆