0

I have this jQuery code which pops out the confirm box when a user clicks any link within a div. But if I click a link the confirm box at first, it pops up, if I click cancel the operation is cancelled and the console.log says confirm is not a function and if I click OK the operation is executed and the console.log says confirm is not a function also then if I click a link again the confirm box doesn't pops up again until I reload the page.

Please do anyone know what I am getting wrong?

$("#aye a").click(function() {
  str = "Removing this Photo, It can not be reversed\nAre You sure You want to remove it?";
  confirm = confirm(str);
  if (confirm) {
    $("#div").html("deleted");
  }
});
<div id="aye">
  <a href="javascript:;">link 1</a>
  <a href="javascript:;">link 2</a>
  <a href="javascript:;">link 3</a>
  <a href="javascript:;">link 4</a>
</div>
<div id="div"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

View on jsFiddle

showdev
  • 28,454
  • 37
  • 55
  • 73
KANAYO AUGUSTIN UG
  • 2,078
  • 3
  • 17
  • 31

2 Answers2

2

You are shadowing window.confirm with a global variable named confirm.

Here is one solution, where I call your local variable confirm2

$("#aye a").click(function(){
    var str = "Removing this Photo, It can not be reversed\nAre You sure You want to remove it?";
    var confirm2 = confirm(str);
    if(confirm2){
        $("#div").html("deleted");
    }
});

Note that I've also added the var keyword to keep those variables from leaking into global space.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
0

$("#aye a").click(function(){
    if(confirm( "Removing this Photo, It can not be reversed\nAre You sure You want to remove it?"))
    {
        // Add class to deleted item and remove click event so user cannot click again
        $(this).addClass("deleted").off("click");
  $("#div").html("deleted");
 }
});
a.deleted{
  color  : silver;
  cursor : not-allowed
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="aye">
   <a href="javascript:;">link 1</a>
   <a href="javascript:;">link 2</a>
   <a href="javascript:;">link 3</a>
   <a href="javascript:;">link 4</a>
</div>
<div id="div"></div>
AsgarAli
  • 2,201
  • 1
  • 20
  • 32