views:

38

answers:

2

I have a link that I would like to present with a confirmation. I am using the javascript confirm() method. But the only way for me to get the link to not work when the user clicks 'cancel' is to use return false;. Is that the correct way to do it (cross-browser)?

$('a.confirm').click(function() {
    if(confirm('Are you sure? This cannot be undone.')) {
        return true;
    }
    return false;
});
A: 

See preventDefault: http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29

$("a").click(function(event){
  event.preventDefault();
});
Jonathan Sampson
+1  A: 

Returning false on an event handler, is equivalent to call both event.preventDefault and event.stopPropagation, your code should work, but what about:

$('a.confirm').click(function() {
  return confirm('Are you sure? This cannot be undone.');
});

It will return false if the user cancels the confirm...

Run that snippet here.

CMS
I knew there was a better way to do it! Thanks!
Andrew