Motive
Motive

Reputation: 3111

.removeData not removing data id

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'));
});

Upvotes: 0

Views: 2136

Answers (1)

Kevin B
Kevin B

Reputation: 95022

You are never updating the id variable to the new value of .data('id')

// Delete confirmation modals
$('#delete-confirm').click(function(e) {
    e.preventDefault();    
    $("#dialog").removeData('id');    
    alert($("#dialog").data('id'));    
});

$('.delete').click(function(e) {
  e.preventDefault();
  $('#dialog').data('id', $(this).data('id'));
});

Also, make sure you aren't binding multiple events to the same element, which could happen with the delete-confirm element. 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.

Upvotes: 3

Related Questions