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 then on
will get its return value as handler which is undefined.
Wrap it an anonymous function so that it will be called when you click
on the checkbox.
$("#checkbox1").on('click', function(){
toggleChecked(this.checked)
});
If you use toggelChecked
method directy as click
handler you can get the checked
status of the checkbox using `this.checked inside the handler.