Posted in jQuery | Posted on 10-19-2009 | 4,031 views
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.
2<a href="http://www.cnn.com">CNN</a><br/>
3<a href="http://www.aetna.com" class="dangerous">Aetnacrap</a><br/>
4<a href="http://www.foxnews.com" class="dangerous">Fox News</a><br/>
5<a href="http://www.yahoo.com">Yahoo</a>
6</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:
2<script>
3
4$(document).ready(function() {
5
6 $("a.dangerous").click(function() {
7 return confirm("Are you sure you want to do this?")
8 })
9
10})
11</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.


<a href="user_delete.cfm?user_id=#user_id#" onclick="javascript: return confirm('Are you sure you want to delete this user permanently from the database?');">Delete</a></td>
thx Ray :)
I've done it with a simple js function and called it on the onClick-Event. So i was able to set a parameter.
For example: onClick="dangerous('delete this file')" and the function would be:
function dangerous(msg) {
confirm('Are you sure you want to ' + msg +'?');
}
something like this i think.
regards.
I almost always add a confirmation step to any hyperlink that leads to a change on the database back-end, especially when such links are bunched together with other clickable items (making the chance of a misdirected click a bit higher).
$('a[href^="http"]')
You would then modify Ray's click function as follows to put out an alert for all external links:
$('a[href^="http"]').click(function() {
return confirm("Are you sure you want to do this?")
}
This way you do NOT have to add unnecessary, non-semantic code.
I simply changed the CSS tag 'dangerous' to something more 'me' friendly. Everyones happy.
@Bill Did you change "dangerous" to "mostlyHarmless"? :)
[Add Comment] [Subscribe to Comments]