jQuery/Javascript confirm coming up twice

♀尐吖头ヾ 提交于 2019-12-05 16:28:37

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.

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

      }
    }

});

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.

Did you try removing that not-used var confirm?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!