I want to count how many checkboxes on my page are selected using jQuery. I\'ve written the following code:
var numberOfCheckboxesSelected = 0;
The first argument passed to the callback in each is the index, not the element. You should use this or a second argument:
$(':checkbox').each(function(idx, checkbox) {
if (checkbox.attr('checked'))
numberOfCheckboxesSelected++;
});
Moreover, the easier way to do this is to select only the checked elements with the :checked selector and then check the selection's length property:
var numberOfCheckboxesSelected = $('input:checkbox:checked').length;