In my project, I’m working on a function which deletes rows from a table and also from the database using .ajax(). I’ve created my function for when the user clicks on the delete button. As you can understand, there a several rows and every row has its own delete button.
Now, when the user clicks on one of them for the first time, a popup modal appears with the question if he/she is sure about deleting the item. When he/she clicks yes, the popup disappears and the row fades-out. This all works perfectly, but…
When you click on a second delete button without refreshing the page, JavaScript fires off the current requested delete (and id) + de previous one. If you do it for a third time, it will fire of the current one and the two previous ones.
I tried to empty the current var $(this).attr('data-page-id');, but it still does the same thing when the .ajax() success function gets fired.
$('a.btn-page-delete').click(function() {
var curPageId = $(this).attr('data-page-id');
$('#delete-page').modal('show');
$('a#action-confirm').click(function() {
$.ajax({
type : 'POST',
url : '/pages/async/delete',
dataType : 'json',
data : { page : curPageId },
success : function(data) {
$('#delete-page').modal('hide');
console.log(curPageId);
console.log(data);
},
error : function() {}
});
});
});
When your outer click event handler gets called
it’ll
.bind()another click event handler to$('a#action-confirm')everytime. So, everytime the outer event is executed you add one more event handler.I’m sure you can and should re-build and construct this in a better way, but in the present state your only choice is to
.unbind()/.off()the inner click handlers, likethat will remove any click event handler bound via jQuery previously.
Ref.:
.off()