no_place_for_my_real_name no_place_for_my_real_name - 1 month ago 16
Ajax Question

Tabulated records delete confirmation issue


<td>random_data_1</td><td><button id="random_data_1"></button></td>
<td>random_data_2</td><td><button id="random_data_2"></button></td>
<td>random_data_3</td><td><button id="random_data_3"></button></td>


$('button[id^="random_data_"]').on('click', function() {
$('#modal-delete-confirm').on('click', function() {

I have this code and my problem is:

Every time I trigger a button to open the modal and dismiss that said modal (its sole purpose is to confirm the delete action) without confirming the delete action... let's say:
gets triggered yet dismissed, same goes with
, and when I confirm
, all 3 records get confirmed for deletion.

Why is this behaving as such? I'm suspecting instances of the event gets duplicated and once confirmed, all instances gets executed. Am I wrong? Coz it's as if the
call gets triggered multiple times depending on how many click events (bound to button[id^=random_data_]) are triggered.


Though you only provided only a portion of your code, but if you are using bootstrap modal, than your suspicion is probably right: every time you click on a button, a new click handler is added to #modal-delete-confirm - but the existing click handlers remain as well. Even if you click the same button three times, and dismiss the modal three times, three click handlers will be attached to the button.

I would add the click handlers only once, and pass the data somehow to the button, e.g.

$('button[id^="random_data_"]').on('click', function() {

$('#modal-delete-confirm').on('click', function() {
    var which = $(this).data('which');
    if (typeof which == 'undefined') {
        console.log('How could this possibly happen?');
    console.log("has to delete " + which);
    // Now do the thing based on the value of which