[jQuery] Count how many checkboxes are checked
Hi, I'm new to JQuery and I have a question about checkboxes. I have
5 checkboxes on my page and they are passed into my plug-in. I'd like
to find out how many of them are checked in my plug-in. The following
code works but I'm sure there is a better way to do it (especially the
part of the code that figures out the number of checkboxes checked).
Any suggestions would be appreciated. Thank you.
=====
In my aspx page:
// $('.category-list') returns a list of 5 checkboxes.
$(function() {
$('#info-heading').createCategoryGroup($('.category-list'));
});
=====
In my plug-in:
// categoryList is a list of checkboxes.
(function($) {
$.fn.createCategoryGroup = function(categoryList) {
var heading = this; // This is an anchor.
// Figure out how many checkboxes are checked when the user clicks
// on any one of the checkboxes.
categoryList.click(function() {
// Figure out the number of checkboxes that are checked.
var checkedCount = 0;
categoryList.each(function() {
if (this.checked) {
checkedCount++;
}
}); // End of each.
// Set the heading to a different color based on how
// many checkboxes are checked.
heading.css('color', checkedCount == 0 ? 'black' : 'red');
}); // End of click.
return this;
}
})(jQuery);