JavaScript Confirm Action Dialog

If you want to create a link that performs an action that can't be rolled back then you might want to stop the user from clicking that link unless they really want to. The best way to do this is to intercept the link with a confirm() command.

The first way to do this (and especially useful if you want to ad other functionality) is to use the following function.

function confirmDelete(delUrl) {
 if (confirm("Are you sure you want to delete")) {
  document.location = delUrl;

For each link that you want to use this function on just replace the href with a simple bookmarklet like the following, pass the URL you want to use within this function call.

<a href="javascript:confirmDelete('')">Delete</a>

Another way is to use the href attribute in the usual way, but to add an onclick event that intercepts the user clicking on the link. The confirm() function returns true or false if the user clicks ok or cancel respectively. With the addition of the return the onclick command will follow the link if the user clicks ok.

<a href="" onclick="return confirm('Are you sure you want to delete?')">Delete</a>

This is an accessible way of creating a system, especially if you know that some of your users will not be using JavaScript. However, you should be very aware when using this functionality that some bad things can happen. For example, if a search engine happens to come across a page with these link on it will click them all and you will find data in your system disappearing! This is a known gotcha and the only way around it is to simply use a button to run any action that destructs data.

Add new comment

The content of this field is kept private and will not be shown publicly.
8 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.