2

I have 2 checkboxes that one selects the other. Checkbox1 has a change event. However, when I check checkbox1 via checkbox2, the event on checkbox1 is not being triggered.

See jsfiddle.

$(document).ready(function() {
     $("#check1").change(arrangeWindow);
   $("#check2").click(function(){
      $("#check1").prop("checked", this.checked);
   });
});

function arrangeWindow() {
    console.log("Missing my baby");
}
<input type="checkbox" id="check1" value="value" />
<label for="chk">Checkbox 1</label>

<input type="checkbox" id="check2" value="value" />
<label for="chk">Checkbox 2 </label>

I can call arrangeWindow from check2 click function, but that's not smart.

How can I trigger the change event upon changing it via jquery?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Dejell
  • 13,947
  • 40
  • 146
  • 229

1 Answers1

2

Programmatically changing the checked property does not raise an event on the element. If you need that behaviour you can use trigger('change') manually:

$(document).ready(function() {
  $("#check1").change(arrangeWindow);
  $("#check2").change(function(){
    $("#check1").prop("checked", this.checked).trigger('change');
  });
});

function arrangeWindow() {
  console.log("Missing my baby");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check1" value="value" />
<label for="chk">Checkbox 1</label>

<input type="checkbox" id="check2" value="value" />
<label for="chk">Checkbox 2 </label>

Also note that you should always use the change event when dealing with checkboxes and radios for accessibility reasons, as that event can be fired on the element using the keyboard.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • why is change preferred over click? – Dejell Aug 16 '16 at 10:44
  • Also `jQ.change()` could be sued instead of `jQ.trigger('change')` but it could come under _Developers preference.._ – Rayon Aug 16 '16 at 10:46
  • 1
    @Rayon Yeah, that's more of a preference. I prefer `trigger('event')` as the purpose of the call is clearer. – Rory McCrossan Aug 16 '16 at 10:49
  • @RoryMcCrossan there is something weird with it. If my arrangeWindow() action takes half a second, the checkbox will be checked ONLY after the action is completed. this is very annoying. any way that it will first select the checkbox and then trigger the change? – Dejell Aug 16 '16 at 12:12
  • 1
    Put the call to `arrangeWindow()` in a `setTimeout`, like this: `setTimeout(arrangeWindow, 1);` – Rory McCrossan Aug 16 '16 at 12:13