问题
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:
- When submit is pressed, alert pops up with "Are you sure?"
- If user hits "yes" then run the script
- 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