JavaScript Confirm Action Dialog

2nd September 2009

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.

  1. function confirmDelete(delUrl) {
  2. if (confirm("Are you sure you want to delete")) {
  3. document.location = delUrl;
  4. }
  5. }

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.page?id=1')">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="delete.page?id=1" 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.