Dejell Dejell - 3 months ago 18
Javascript Question

Change of checkbox doesn't trigger function

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?

Answer

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.