Suppose you have a 'back office' interface for a website that presents a list of 'products', with the option of editing or deleting each one. Your product list may then look something like the following:
When you click on one of the 'Delete' links in this example, you will be prompted to 'confirm' your action. This is a way of ensuring that items are not accidentally deleted, or the wrong item deleted by mistake.
Note: For the security-conscious, forms of this type, particularly those that use GET variables to trigger events, are very susceptible to Cross-site request forgery (CSRF) attacks, which are very difficult to protect against. More on that later.
The syntax to add the 'confirmation prompt' is surprisingly simple:
<a href="..." onclick="return confirm('Are you sure?');">Delete</a>
Note: Some browsers will present the options as OK/Cancel and others as Yes/No. You can't change the buttons, the title or the format of the dialog box, so it's best to just pose a question for which both sets of options make sense.
In less technical terms: when the link is clicked, the confirm box is presented. If you click on Yes (or OK) then a value of true is returned and the href link is triggered. If you click on No (or Cancel) then a value of false is returned, which cancels the href action, meaning that the browser does not follow the link.
<a href="someimage.gif" onclick="window.open('someimage.gif'); return false;">show image</a>
In cases where you really want the user to be sure of their actions, you can add a second confirmation prompt requiring the user to twice confirm the action:
<a href="..." onclick="return confirm('Are you sure?') && confirm('Are you really sure?');">Delete</a>
If you're displaying data using PHP, then you will need to escape any quotes present in the confirmation prompt:
... onclick="return confirm('Delete this item: <?PHP echo addslashes($itemname) ?>?');" ...
Send a message to The Art of Web:
press <Esc> or click outside this box to close