jQuery/Javascript confirm coming up twice

12,857

Solution 1

Do you load any content dynamically (via ajax)? It could be the case that the click event is bound to the same element twice resulting in the double confirmation.

Solution 2

It happens when we bind event on the elements which are loaded dynamically via AJAX

So for example we are loading some dynamic html content (e.g. dynamic content in modal) on click of the edit form button,

And in that content if we have binded click event on some button e.g. delete button, then every time we click on edit form button, it binds the click event to delete button every time,

And if you have set confirm box on click event of delete button then, it will ask you as many time as it was binded for that click event means here if we have clicked edit form button 5 times then it will asks for your confirmation 5 times.

So for solving that issue you can unbind the event every time before binding event to dynamically loaded element as following :

$(document).off('click', '.DeleteComment').on('click', '.DeleteComment', function () {
   if (confirm('Are you sure you want to permanently delete this comment?')){
      //Delete process
      return true;
   }
   return false;
}

Or Another way to solve this problem is to add your script in main page, means static page not in dynamically loaded one.

Solution 3

try this:

$_blockDelete = false;

$(".DeleteComment").live("click", function(event){

    event.preventDefault();
    //event.stopPropagation(); // it is not necessary

    if (!$_blockDelete)
    {
      $_blockDelete  =true;
      var rconfirm = confirm('Are you sure you want to permanently delete this comment?');
      if (rconfirm)
      {
          $(this).html("loading").css("color", "#999");
          var CommentID = $(this).attr("rel");
          //AJAX HERE
          //return the value "false" the variable "$_blockDelete" once again ajax response

      }
    }

});
Share:
12,857
Adam
Author by

Adam

Student, web developer, photographer.

Updated on June 21, 2022

Comments

  • Adam
    Adam almost 2 years

    For some weird reason i'm getting my confirm box coming up twice. here is my code:

    $(".DeleteComment").live("click", function(){
    
        var CommentID = $(this).attr("rel");
        var confirm
    
        if (!confirm('Are you sure you want to permanently delete this comment?')){
    
            return false;
    
        }else{
            $(this).html("loading").css("color", "#999");
            //AJAX HERE
            return false;
        }
    
    
    });