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?
In the most simple way, you can use the confirm() function in an inline onclick handler.
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.
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With