I have the following code that shows a dialog box to confirm if an item should be deleted. The problem is, every time I click the delete button, the id of the item is added to #dialog data every time.
So the first time I delete, it alerts just the id like I’d expect. If I click another item to delete, it shows the previous id as well. How can I clear the data attached to dialog properly?
// Delete confirmation modals
$('#dialog').on('show', function() {
var $this = $(this);
var id = $this.data('id');
$('#delete-confirm').click(function(e) {
e.preventDefault();
$this.removeData('id', id);
alert(id);
});
});
$('.delete').click(function(e) {
e.preventDefault();
$('#dialog').data('id', $(this).data('id'));
});
You are never updating the
idvariable to the new value of.data('id')Also, make sure you aren’t binding multiple events to the same element, which could happen with the
delete-confirmelement. Confirm by making the dialog appear multiple times, and confirming the delete multiple times. if the alert starts happening more and more times, then you are re-binding the event.