Quick example - jQuery code to add confirmations to links

I'm not a big fan of confirmations. I mean, if I wasn't sure I wanted to do some action than I wouldn't have clicked the link, right? But sometimes clients ask us to add such confirmations to potentially dangerous operations, like deletes for example. Here is a super simple example of how to quickly add a confirmation to a range of actions on a page - delete or whatever. To begin - lets add a class to links that we want confirmations on. For fun we will call them dangerous links.

<p> <a href="http://www.cnn.com">CNN</a><br/> <a href="http://www.aetna.com" class="dangerous">Aetnacrap</a><br/> <a href="http://www.foxnews.com" class="dangerous">Fox News</a><br/> <a href="http://www.yahoo.com">Yahoo</a> </p>

Noticed that for the four links, I've only marked two of them as dangerous. (And yes, I'm being political and angry so please forgive me. If the text bothers you, ignore it.)

Now for the code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script>

$(document).ready(function() {

$("a.dangerous").click(function() {
    return confirm("Are you sure you want to do this?")

}) </script>

As you can see, I simply create a selector to match all anchor tags with a class of dangerous. I bind to the click function and return true or false based on how you answer the confirmation dialog. Notice I kept the message vague. I didn't mention "delete" or any other particular action. I just gave a simple warning.

That's it. Hope this is helpful for others.

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.