I am trying to use the on method for future DOM elements, but for some reason instead of calling events on click, it fires them when the DOM objects are dynamically created.
here’s the code that I have.
$("#checkbox1").on('click', toggleChecked(this.checked)); //this is included in Ajax call success method
function toggleChecked(status) {
$(".item").each(function () {
$(this).prop("checked", status);
});
}
What am I doing wrong here?
toggleChecked(this.checked)will right away execute the function and thenonwill get its return value as handler which is undefined.Wrap it an anonymous function so that it will be called when you
clickon the checkbox.If you use
toggelCheckedmethod directy asclickhandler you can get thecheckedstatus of the checkbox using `this.checked inside the handler.