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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

why is change preferred over click?
Also jQ.change() could be sued instead of jQ.trigger('change') but it could come under Developers preference..
@Rayon Yeah, that's more of a preference. I prefer trigger('event') as the purpose of the call is clearer.
@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?
Put the call to arrangeWindow() in a setTimeout, like this: setTimeout(arrangeWindow, 1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.