Count checkboxes within element
I'm trying to find a way to count all checked checkboxes within a parent element using jQuery. Sofar I haven't found a decent (and fast) solution.
To illustrate the situation: I've got an ul-list with one 'check-all' checkbox, and one checkbox per child list-item. When there are no checked list-items, I want the check-all checkbox to be unchecked. Therefore I assume I've to count all the checked list-items each time one of them is changed.
[...]
<li><input type="checkbox" class="checkall" />
<ul>
<li><input type="checkbox" id="ch1" class="list" /></li>
<li><input type="checkbox" id="ch2" class="list" /></li>
<li><input type="checkbox" id="ch3" class="list" /></li>
</ul>
</li>
[...]
As you can see I'm working with a nested ul-list, for the record. Sofar I've got the following jQuer开发者_如何转开发y code, which serves for selecting the parent list-item, as I've only got to count the checkboxes within that 'group'.
// $(this).val() is neccesary for my code to know which checkbox has been affected
var parentnode = $('input#' + $(this).val()).parent().parent().parent();
alert(parentnode.children('input.list:checked').length);
I know it won't work using the children selector (that's for looping, right?), but I can't find a way to count the checked checkboxes length from the 'parentnode' element.. Can you help me out?
Since children() only processes the direct children of your element, you can use find() instead to process all descendants matching the selector:
alert(parentnode.find('input.list:checked').length);
精彩评论