Sometimes, we want to show a “are you sure?” dialog when we click on a link with JavaScript or jQuery.
In this article, we’ll look at to show a “are you sure?” dialog when we click on a link with JavaScript or jQuery.
How to show a “are you sure?” dialog when we click on a link with JavaScript or jQuery?
To show a “are you sure?” dialog when we click on a link with JavaScript or jQuery, we can call the confirm
function in the click event handler of a link.
For instance, we write:
<a href="/DoSomethingDangerous" class='confirm'>do something dangerous</a>
to add the link.
Then we write:
$(() => {
$('.confirm').click((e) => {
return window.confirm("Are you sure?");
});
});
We select the link with $
.
And we call click
with the click event handler for the link.
In the click event handler, we call window.confirm
with the text we want to show in the dialog.
Now when we click on the link, we see ‘Are you sure?’ displayed.
And we can click OK or Cancel to dismiss it.
Conclusion
To show a “are you sure?” dialog when we click on a link with JavaScript or jQuery, we can call the confirm
function in the click event handler of a link.