Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox click event firing twice

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!

like image 420
iamjc015 Avatar asked Apr 18 '15 05:04

iamjc015


Video Answer


1 Answers

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 Delegation

Event 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.

like image 71
Nishit Maheta Avatar answered Oct 03 '22 05:10

Nishit Maheta