I am trying to make an ajax call to delete a user making use of a bootstrap modal.
The modal is used for confirmation purposes and it is the following.
<!-- Modal -->
<div id="deleteModal" class="modal hide fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Delete user</h3>
</div>
<div class="modal-body">
<p>You are about to delete this user. Are you sure that you want to continue?</p>
</div>
<div class="modal-footer">
<button id="confirm" class="btn btn-primary">Yes</button>
<button id="cancel" class="btn" data-dismiss="modal" aria-hidden="true">No, leave</button>
</div>
</div>
Then I am using the following javascript to process the user input
$('a#delete').click(function(e){
var anchor = this;
$('#deleteModal').modal('show');
$('button#confirm').click(function(e){
$('#deleteModal').modal('hide');
$.ajax({
url: $(anchor).attr('href'),
success:function(result){
$(anchor).closest('tr').addClass("error");
$(anchor).closest('tr').delay(2000).fadeOut();
}});
});
return false;
});
The link that user has to click is like this
<a id="delete" href="/admin/edit/user/delete/30" class="btn btn-danger" user="30"><i class="icon-trash"></i> Delete</a>
It works but I noticed that something weird happens. If I click to delete one user and I choose to cancel the action from the modal and then I choose to delete another user confirming the action, both users are deleted.
I think that the rule I have declared still applies in the objects that have been clicked during a session. Is there a way to avoid this?
It is because of the way in which you are registering the
clickevent onbutton#confirm. Every time you click on the delete button you are registering a new click event handler to the modal dialog’s confirm button.Problem with you approach is demonstrated here.
It can be fixed by splitting the logic into two parts
Here we registers the
confirmclick event only once at the page loading, but when the delete button is clicked we pass a context information to the confirmation modal via theuserattribute. In the confirm callback we use this context information to determine which user has to be deleted.You can test it in the demo here.