11

I have a form which allows the user to delete some data from a database.

I want to have a bit of confirmation to prevent accidental deletes. I want to do the following:

  1. When submit is pressed, alert pops up with "Are you sure?"
  2. If user hits "yes" then run the script
  3. If user hits "no" then don't submit the script.

How can this be done?

I have added the onSubmit alert but it does not show anything, and it still submits the form. How can I delay the submission of the form to only occur when the user selects "yes" from the alert?

<form 
  method="POST"
  action="actions/remove-daily-recipient.php"
  onSubmit="alert('Are you sure you wish to delete?');"
>
  ...
</form>
mit
  • 11,083
  • 11
  • 50
  • 74
Francesca
  • 26,842
  • 28
  • 90
  • 153
  • Does this answer your question? [JavaScript Form Submit - Confirm or Cancel Submission Dialog Box](https://stackoverflow.com/questions/6515502/javascript-form-submit-confirm-or-cancel-submission-dialog-box) – Flimm Nov 11 '21 at 09:29

3 Answers3

30

Instead of alert, you have to use confirm and return in your form, for an example:

<form 
    method="post"
    onSubmit="return confirm('Are you sure you wish to delete?');">
...
</form>
Ícaro
  • 1,432
  • 3
  • 18
  • 36
3

on your form can you try with a js function like:

<form onsubmit="return submitResult();">

and on your function have something like?

function submitResult() {
   if ( confirm("Are you sure you wish to delete?") == false ) {
      return false ;
   } else {
      return true ;
   }
}

I think this will be a good start.

-1

Stop the default behaviour, ask for confirmation and then submit the form:

var form1 = document.getElementById('form1');
form1.onsubmit = function(e){
   var form = this;
   e.preventDefault();
   if(confirm("Are you sure you wish to delete?"))
       form.submit();
}

JS Fiddle: http://jsfiddle.net/dq50e963/

Anurag Peshne
  • 1,547
  • 12
  • 29
  • By using this solution I lose my data that I was submiting with form i.e. in the backand the data is missing. How would you forward the data after preventing the default submission this way? – dsalaj Oct 23 '15 at 07:54
  • @dsalaj: if the submission is prevented, how will the form data reach the server. Isn't this the required behaviour? – Anurag Peshne Oct 23 '15 at 08:19
  • @AnuragPeshne What I meant is after the successfull confirmation and submission. When the `form.submit()` is executed after the user confirms the action, the form is submited but without the data. I don't think that that was required behaviour. – dsalaj Oct 23 '15 at 10:45