Link to home
Start Free TrialLog in
Avatar of Jazzy 1012
Jazzy 1012

asked on

Conformation code

I have this javascript
function CancelAll() {
	confirm("Are you sure you want to cancel everything?")
}

Open in new window

Here is the button:
<a onclick='return CancelAll()' href="cancel.php?id=<?=$id?>">
<input  style="margin-top: 20px" type="button" class="bbt"  value="CANCEL ALL">
</a>

Open in new window

How can I make it that if the user clicks okay on the conformation for it to go to that click, else not to, because now even if I click on cancel, it still goes to that link
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

HTML
<a id="anchor" onclick='return CancelAll()' href="cancel.php?id=<?=$id?>">
<input  style="margin-top: 20px" type="button" class="bbt"  value="CANCEL ALL">
</a>

Open in new window


js code:
function CancelAll() {
	if(confirm("Are you sure you want to cancel everything?")){
      window.location=document.getElementById('anchor').href;
    }
}

Open in new window


Or JQuery:

function CancelAll() {
	if(confirm("Are you sure you want to cancel everything?")){
      window.location=$('#anchor').href;
    }
}

Open in new window

Avatar of Jazzy 1012
Jazzy 1012

ASKER

No none of them worked, it still went to that url
ASKER CERTIFIED SOLUTION
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It is actually much simpler than that. A bit of history about click events and confirmation boxes.

A click event handler should return a true or false value. A true value is the default if none is specified. If you return false it cancels the click event.

In other words

If you say
<a href="xyz.html" onclick="return someFunction()">xyz.html</a>

Open in new window


Then if someFunction() returns false - the click default will be overridden.

The confirmation() function returns false (if Cancel is clicked) and True if (Ok) is clicked so you can simply do this
<a onclick='return CancelAll()' href="cancel.php?id=<?=$id?>">
<input  style="margin-top: 20px" type="button" class="bbt"  value="CANCEL ALL">
</a>

<script>
function CancelAll() {
	return confirm("Are you sure you want to cancel everything?")
}
</script>

Open in new window