Adam
Adam

Reputation: 9449

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


});

Upvotes: 6

Views: 14915

Answers (4)

Haritsinh Gohil
Haritsinh Gohil

Reputation: 6272

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.

Upvotes: 5

andres descalzo
andres descalzo

Reputation: 14967

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

      }
    }

});

Upvotes: 4

Marek Karbarz
Marek Karbarz

Reputation: 29294

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.

Upvotes: 14

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

Did you try removing that not-used var confirm?

Upvotes: 0

Related Questions