Counter counting 1 higher than expected value in jQuery.each()

Viewed 27

I have this function that iterates over all checkboxes in a table and checks them. I also made a counter that will count the number of rows checked. Interestingly, the counter always returns one higher than my expected value. The counter is initialized as 0, so I expect it to increment for every checkbox but something else seems to be going on. Anyone know why this is?

var counter=0;
$('#checkAll').click(function (event){
 $(':checkbox').each(function(){
  this.checked=true
  counter+=1
  });
});

Minimal reproducible example: https://codepen.io/enyu0510/pen/eYrEgJe

2 Answers

You have four checkboxes on this page including the select all checkbox - that’s why this is happening. You will need to be more specific and target only the list item checkboxes. One way to do this would be to name the checkboxes you want to count like name=list-checkbox For example - And then target those checkboxes like like $(“[name=list-checkbox]”)

Updating answer to this question because OP update it with the example of the code that is not working

Updated answer

Reason why you are getting value higher than expected is because you have 4 checkboxes in that example. You have to target checkbox list/group in a more specific way (e.g. by their name) because with $(':checkbox') you are counting all checkboxes on the page

Old asnwer

Above code looks fine. Working as expected https://jsfiddle.net/vwxcap9o/.

Make sure to check that there isn't any other checkbox on that page, maybe that's the reason why you are receiving wrong number. Also, try to target that checkbox group in different way than $(':checkbox').

Related