Andrew
Andrew

Reputation: 239087

How to disable click with jQuery/JavaScript?

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;
});

Upvotes: 0

Views: 715

Answers (2)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827962

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.

Upvotes: 3

Sampson
Sampson

Reputation: 268462

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

$("a").click(function(event){
  event.preventDefault();
});

Upvotes: 0

Related Questions