简体   繁体   中英

How to get the number (count) of selected checkboxes?

I have following code

<ul class="myfilterside  catfilter">
<li>
    <input type="checkbox"  value="1" class="filter" name="Bedroom">
    <a id="1" href="javascript:void(0)" class="filter1"> test1 </a>
</li>

<li>
    <input type="checkbox"  value="2" class="filter" name="Corridor">
    <a id="2" href="javascript:void(0)" class="filter1"> test2 </a>
</li>

<li>
    <input type="checkbox"  value="3" class="filter" name="Test">
    <a id="3" href="javascript:void(0)" class="filter1"> test3 </a>
</li>

</ul>
<input type="button" value="Clear All" class="check">
<script>
jQuery('.check:button').click(function(){ 
            jQuery('.filter').removeAttr('checked');                    
            jQuery(this).val('Clear All');              
        }); 
</script>       

On clicking the button I want to get the count of all selected checkboxes. That means if two checkboxes are checked the I want to get the count =2 How can I do this?

您可以使用:checked获得选中的复选框

var checked = $('.filter:checked').length;

You can use :checked selector to get the checked checkboxes and length to get the total number of these checkboxes:

var length = $('.filter:checkbox:checked').length;

Fiddle Demo

You can use

$(".filter:checked").length

Refer this link for more details about :checked selector

Try this

jQuery('.count:button').click(function(){ 
    var count =0;
    $("input.filter:checkbox").each(function(){
        if($(this).is(':checked') ){
            count++;   
        }
    });
    alert(count);
}); 

Demo

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