Ajax Question

Tabulated records delete confirmation issue

HTML:

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


JQUERY:

//document.ready
$('button[id^="random_data_"]').on('click', function() {
$('#modal').modal('show');
$('#modal-delete-confirm').on('click', function() {
$.ajax({
...
});
});
});


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:
#random_data_1
gets triggered yet dismissed, same goes with
#random_data_2
, and when I confirm
#random_data_3
, 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
ajax
call gets triggered multiple times depending on how many click events (bound to button[id^=random_data_]) are triggered.

Answer

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').data('which', this.id);
    $('#modal').modal('show');
}); 

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