20 January, 2012

Form submission with alert/confirm

This has been a perennial issue for me. I'd have a form with multiple submit buttons; and on one or more - but not all - of the submit buttons I would want a confirm dialogue. 'Save' or 'Amend' might go straight through but 'Delete' would be intercepted for a confirmation. I used to put a section in the form response page setting up another form with a confirm button. But I think I have found a more elegant solution, below (though it does rely on JavaScript being enabled).

In the form add a hidden field and submit button as follows:
<input type="hidden" name="confirm_delete" id="confirm_delete" value="0" />

<input type="submit" name="delete" value="Delete" onClick="confirmDelete(this.form);" />

Add a JavaScript function like this:
function confirmDelete(form) {
var answer = confirm("Are you sure you want to deleted this?");
if (answer == true) {
form.confirm_delete.value = 1;
Then you can handle the confirmed deletion by testing the hidden field
if($_POST['confirm_delete'] == 1){
// do whatever needs doing