简体   繁体   中英

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

HTML is the following:

<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?

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.

Instead try:

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

There is a specific :checkbox pseudo selector. It does the same as 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.

You could reduce it slightly, to the following, if you know there are no other checkable inputs:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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