Sometimes, we want to show a confirm or cancel submission dialog box when submitting a form with JavaScript.
In this article, we’ll look at how to show a confirm or cancel submission dialog box when submitting a form with JavaScript.
How to show a confirm or cancel submission dialog box when submitting a form with JavaScript?
To show a confirm or cancel submission dialog box when submitting a form with JavaScript, we add aa submit event handler to the form.
For instance, we write
<form>...</form>
to add a form.
Then we write
const validate = () => {
// ...
if (!valid) {
alert("Please correct the errors in the form!");
return false;
} else {
return confirm("Do you really want to submit the form?");
}
};
const form = document.querySelector("form");
form.onsubmit = validate;
to define the validate
function.
In it, we check if valid
is true
.
If it’s not, we show an alert and return false
to stop the submission.
Otherwise, we return a confirm box so the user can choose whether the form should be submitted or not.
Then we select the form with querySelector
.
And we set its onsubmit
property to the validate
function.
Conclusion
To show a confirm or cancel submission dialog box when submitting a form with JavaScript, we add aa submit event handler to the form.