1

I have multiple input checkbox with a class name generated in a foreach loop :

<input type="checkbox" class="division_1">

<input type="checkbox" class="division_2">

<input type="checkbox" class="division_3">

i need to find a way to write the good selector for this case but actually i get this error :

Syntax error, unrecognized expression: .division_[object Object]

here my javascript :

 var i;

            for (i = 1; i < 7; i++) {
                $("#checkAllDivisions").click(function (i) {
                    $('.division_' + i).each(function() {
                        this.checked = true;
                    });
                });
            }
Mathieu Mourareau
  • 1,140
  • 2
  • 23
  • 47
  • Why not give an additional simple classname and use that for this purpose. Like: class="division division_N". You are trying to use class like an ID. – Nawed Khan Mar 03 '20 at 17:19

1 Answers1

1

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339