Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/Javascript confirm coming up twice

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


});
like image 340
Adam Avatar asked Nov 26 '09 01:11

Adam


3 Answers

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.

like image 102
Marek Karbarz Avatar answered Nov 06 '22 23:11

Marek Karbarz


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.

like image 5
Haritsinh Gohil Avatar answered Nov 06 '22 23:11

Haritsinh Gohil


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

      }
    }

});
like image 4
andres descalzo Avatar answered Nov 07 '22 00:11

andres descalzo