Add a confirmation alert before submitting a form

大城市里の小女人 提交于 2020-05-12 02:49:32

问题


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>

回答1:


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>



回答2:


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.




回答3:


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/



来源:https://stackoverflow.com/questions/27921283/add-a-confirmation-alert-before-submitting-a-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!