The Netlobo logo - a Nevada desert landscape

Delete Confirmation using Javascript

Learn to use javascript to make users confirm that they really want to delete something.

Published Jul 29, 2005 by lobo235
Last updated on Jan 21, 2008

When writing many types of web applications you will find a need to let a user delete something. In eCommerce, for example, you may want the user to be able to setup different shipping addresses so they can ship items to friends or family during the holidays. It would be nice to let them delete old addresses to keep their list of shipping addresses organized and up-to-date. In photo gallery applications you may users to be able to not only add photos to their photo gallery but to delete them as well.

In my experience I have seen that it is almost always a good idea to have the user confirm that they really want to delete something before actually deleting it. It is possible that the user clicked on the delete link accidentally or that they made a last minute decision that they didn't want to delete the item. There are many ways to do this but one of my favorites is by using a bit of Javascript to bring up a confirm message which allows the user to choose whether they really want to delete the item or not. The only disadvantage to this method is that some people will have javascript turned off in their browsers. To get around this obstacle you can check to see if they had javascript disabled and if so, do the confirm by displaying another page that asks them if they want to delete or not. Javascript is nice because you do not have to load up another page so it can be done quickly and efficiently. Here is the javascript function that I use in any links that delete data on my pages.

function confirmDelete()
{
    return confirm("Are you sure you wish to delete this entry?");
}

To use this, just set the onclick attribute of an <a> element to return confirmDelete(). When the user clicks the link it will bring up a confirmation message with an "OK" or "Cancel" option. If they choose "OK" it will take them to the link's location. If they choose "Cancel" then nothing happens. This javascript function is very simple and it's easy to add to any existing site. Here is an example of how you would use it with a link:

<a href="?action=delete&id=3" onclick="return confirmDelete();">
    Delete this entry
</a>

So the actual link would look like this: Delete this entry. You will need to write a PHP script (or other server-side script) to actually delete the entry.

I hope that this article will be useful to you. Please let me know if you have any questions or comments.

5 comments for this article.

del.icio.us logo add this article to del.icio.us!
Other great Web Development and Programming articles on Netlobo.com:
Showing and Hiding a DIV using CSS and Javascript
Disable Form Buttons and Other Elements with Javascript
Persistent Login Cookies Done Right