I am using jQuery DataTables inside a modal. From that table I have a column in which it contains checkboxes. The first attempt in getting values of the checked checkboxes is all ok. However, when I close the modal and choose again, the checkbox click event is firing 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 response will be greatly appreciated. Thanks!
use below code. add .off("change")
before attach event.
read more about .off()
Remove an event handler.
I assume you attach change event every time when model box 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);
}
});
other option is attach event every time you can use
Event Delegation
to attach event to dynamic generated element . you can read more about Event DelegationEvent delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With