Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript or jQuery "Are you sure?" dialog for <A> link?

I have a link in my HTML:

<a href="/DoSomethingDangerous">do something dangerous</a> 

Visiting the DoSomethingDangerous link causes a not easily reversable action to occur.

So after the link is clicked on I would like a dialog box (eg "Are you sure?" "OK" "Cancel") to be displayed and if the user clicks Cancel the link is not visited and the browser remains at the same page.

What is the cleanest technique using either Javascript or jQuery to implement this?

like image 905
Andrew Tomazos Avatar asked Sep 21 '12 13:09

Andrew Tomazos


People also ask

How do you display a confirmation dialog when clicking an a link?

In the most simple way, you can use the confirm() function in an inline onclick handler.

Can I use both JavaScript and jQuery together?

jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery.


1 Answers

<a class="confirm" href="/DoSomethingDangerous">do something dangerous</a> 

JQuery:

$(function() {     $('.confirm').click(function(e) {         e.preventDefault();         if (window.confirm("Are you sure?")) {             location.href = this.href;         }     }); }); 

or even simpler:

$(function() {     $('.confirm').click(function() {         return window.confirm("Are you sure?");     }); }); 

The native confirm box can't be styled. If you want style, then you could use jQuery.UI.dialog

like image 140
xdazz Avatar answered Sep 28 '22 18:09

xdazz