...

View Full Version : Confirmation when clicking a link



ben1390
12-04-2009, 03:22 PM
Hi all, I want to have a javascript popup box so that when a hyperlink is clicked, a user is asked if they are sure they want to click this link, if they select ok then the page loads, if they click canel then nothing happens, so i have this code below:


<script type="text/javascript">
function confirmSubmit()
{
var agree=confirm("Are you sure you wish to click this link?");
if (agree)
return true ;
else
return false ;
}
</script>


<a onclick="return confirmSubmit()" href="page.html">Page</a>

However when a user clicks cancel the link still loads, can anyone see where I am going wrong? any help will be appreciated

Spudhead
12-04-2009, 03:38 PM
function confirmSubmit(){
return confirm("Are you sure you wish to click this link?");
}

ben1390
12-04-2009, 03:51 PM
Thank you for that, however it does not work and I still have the same problem

Philip M
12-04-2009, 04:02 PM
Both your original code and Spudhead's condensed version are perfectly correct, and both work fine for me.

But this sort of thing tends to annoy your visitors, who are not complete idiots. They are unlikely to click on the link by accident, and by clicking on a link show that they wish to leave your page.

gusblake
12-04-2009, 07:43 PM
I have had a mess around with some code and that method doesn't work for me either - the return value of the function has no effect on whether the link is followed.

This works in FF 3.5, and probably could be modified to work in others:



window.addEventListener("load",convertlinks,false)

var hrefs=[];
var links;

function convertlinks() {
links=Array.prototype.slice.call(document.getElementsByTagName("a"));
for(i in links) {
hrefs[i]=links[i].href;
links[i].removeAttribute("href");
links[i].addEventListener("click",link_click,false);
}
}

function link_click(e) {
e=e.target||e.srcElement;
if(confirm("yes?")) window.location.href=hrefs[links.indexOf(e)];
}


One thing I noticed is that without an href the link loses its default cursor and styling, which CSS will of course fix if you end up using something like this.

Philip M
12-05-2009, 07:00 AM
Sorry, but this works perfectly in all browsers:-


<script type="text/javascript">
function confirmSubmit() {
var agree=confirm("Are you sure you wish to click this link?");
if (agree) {return true}
else {return false}
}
</script>

<a onclick="return confirmSubmit()" href="http://www.google.com">Page</a>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum