Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checkbox checked with prop() does not fire events attached to "change"

Tags:

boxes checked using jQuery prop() do not affect listeners attached to change handler.

My code is something like

HTML

<div>
    <label>
        <input type="checkbox" class="ch" />test</label>
    <label>
        <input type="checkbox" class="ch" />test</label>
    <label>
        <input type="checkbox" class="ch" />test</label>
    <input type="button" value="check the box" id="select" />
</div>

JS

 $("body").on("change", ".ch", function(){

  alert("checked");

});


$("body").on("click", "#select", function(){

  $(this).parent("div").find("input[type=checkbox]").prop("checked", true);

});

the alert fires when I click on the checkbox. How can I make it fire when the property of the checkbox changes? JSBIN

like image 705
1252748 Avatar asked Oct 21 '13 21:10

1252748


2 Answers

You have to use .change() to trigger the change event listener:

$("body").on("change", ".ch", function () {
    alert("checked");
});


$("body").on("click", "#select", function () {
    $(this).parent("div").find("input[type=checkbox]").prop("checked", true).change();
});

JSBbin or Fiddle

Please note that this will fire many events. Three in the html example you have in jsBin.

like image 199
Sergio Avatar answered Sep 25 '22 12:09

Sergio


Trigger the event from inside your function:

$("body").on("click", "#select", function(){
  $(this).parent("div").find("input[type=checkbox]").prop("checked", true).trigger("change");
});
like image 42
Todd Avatar answered Sep 26 '22 12:09

Todd