The issue is because you've defined i
in the arguments of the click
event handler function which overrides the outer i
variable, and actually defines it as an Event object. This is why the output shows [object Object]
when the object is coerced to a string.
You need to remove it from the arguments list. However, then the issue becomes one of scope as the i
variable will always be 7
by the time any click
can fire. To fix that you need a closure:
// note: do not do this in a production environment, it's just for demonstration purposes!
var i;
for (i = 1; i < 7; i++) {
(function(i) {
$("#checkAllDivisions").click(function() {
$('.division_' + i).each(function() {
this.checked = true;
});
})
})(i);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="checkbox" class="division_1">
<input type="checkbox" class="division_2">
<input type="checkbox" class="division_3">
<button id="checkAllDivisions">Check All</button>
Obviously, that's extremely ugly and not ideal.
A much better solution is to get rid of the incremental classes, as they are an anti-pattern as you can see from the horrible JS code you need to write to work with them, and to instead put the same class on all the checkboxes. Then all your code becomes a simple one-liner:
$("#checkAllDivisions").click(() => $('.division').prop('checked', true));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="checkbox" class="division">
<input type="checkbox" class="division">
<input type="checkbox" class="division">
<button id="checkAllDivisions">Check All</button>