Disable checkbox event
I am using jQuery DataTables inside a modal. From this table, I have a column that contains checkboxes. First attempt to get the values ββof checked flags - everything is fine. However, when I close the modal and select again, the checkbox click event fires twice. Here is my code:
//handle event for checkbox checking.
arresting_officers_table.on("change", ":checkbox", function() {
if($(this).is(':checked')){
console.log('Adding!'); //this log fires twice when clicking only 1 checkbox
//alert('checked! ' + $(this).attr('data-value'));
arresting_officers_ids.push($(this).attr('data-value'));
arresting_officers_names.push($(this).attr('data-name'));
} else {
//remove item
var idx = arresting_officers_ids.indexOf($(this).attr('data-value'));
arresting_officers_ids.splice(idx, 1);
arresting_officers_names.splice(idx, 1);
}
});
Your answer will be greatly appreciated. Thank!
source to share
use below code. add .off("change")
before connecting.
Find out more about . off ()
Remove the event handler.
I am assuming you are attaching a change event every time the model window is open.
arresting_officers_table.off("change").on("change", ":checkbox", function() {
if($(this).is(':checked')){
console.log('Adding!'); //this log fires twice when clicking only 1 checkbox
//alert('checked! ' + $(this).attr('data-value'));
arresting_officers_ids.push($(this).attr('data-value'));
arresting_officers_names.push($(this).attr('data-name'));
} else {
//remove item
var idx = arresting_officers_ids.indexOf($(this).attr('data-value'));
arresting_officers_ids.splice(idx, 1);
arresting_officers_names.splice(idx, 1);
}
});
another option is to attach an event every time you can use
Event Delegation
to attach an event to a dynamically generated element. you can read more about Event DelegationDelegation event allows us to attach a single event listener to a parent that will fire for all descendants matching the selector, whether those descendants exist or are added in the future.
source to share