KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2188

confirm not working after first click: confirm is not a function

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

Upvotes: 0

Views: 536

Answers (2)

AsgarAli
AsgarAli

Reputation: 2211

$("#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>

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

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.

Upvotes: 2

Related Questions