简体   繁体   English

计算已选中多少个复选框

[英]Count how many checkbox have been checked

I am using the following code to check how many checkbox user has checked. 我正在使用以下代码来检查多少个复选框用户已选中。

var empty_watch = $('#clocks').find('input.checkbox:checked').length;

This is used in form validation: if empty_watch is 0 then do not post form: user must choose at least one item (and there is not a default one). 这在表单验证中使用:如果empty_watch为0,则不发布表单:用户必须至少选择一项(并且没有默认项)。

HTML is the following: HTML如下:

<div id="clocks" class="sez-form">
<fieldset>
<legend> Orologi inclusi </legend>
<div class="percheckbox">
    <input class="clock" type="checkbox" value="1" name="orologio">Browser
</div>
<div class="percheckbox">
    <input class="clock" type="checkbox" value="2" name="orologio">Prototipo1
</div>
<div class="percheckbox">
    <input class="clock" type="checkbox" value="3" name="orologio">test FP
</div>
<br style="clear: both;">
</fieldset>
</div>

Even if I check all the checkboxes empty_watch is still 0. What am I doing wrong? 即使我选中所有复选框,empty_watch仍为0。我在做什么错?

Your find selector: 您的查找选择器:

'input.checkbox:checked'

looks for an input with a class of 'checkbox'. 查找带有“复选框”类的输入。 You should be looking at the 'type' attribute of the element. 您应该查看元素的'type'属性。

Instead try: 而是尝试:

'input[type="checkbox"]:checked'

There is a specific :checkbox pseudo selector. 有一个特定的:checkbox伪选择器。 It does the same as input[type=checkbox] : 它与input[type=checkbox]

var empty_watch = $('#clocks').find(':checkbox:checked').length;

As you already target #clock then find, this will be pretty good speed-wise too. 正如您已经将#clock作为目标,然后发现,这在速度方面也是相当不错的。

You could reduce it slightly, to the following, if you know there are no other checkable inputs: 如果您知道没有其他可检查的输入, 可以将其略微减少至以下内容:

var empty_watch = $('#clocks').find(':checked').length;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM