I have a web page where people can either save the form to be able to edit the info later again, or to submit the form. I want to add a confirmation message when the user clicks the submit button. If the user clicks ‘Cancel’ I want the form submission to be cancelled.
I tried the following, but it has no effect:
const form = document.querySelector('#incidentform');
form.addEventListener('onsubmit', function () {
let text = "Are you sure you want to submit?";
if (confirm(text) == true) {
return true;
} else {
return false;
}
});
3
Answers
Use Jquery – To implement a submit button with a confirmation box using jQuery, you can attach a click event handler to the button and display a confirmation dialog. If the user clicks "OK," the form will be submitted, and if the user clicks "Cancel," the form submission will be prevented.
Here’s an example:
When you want to cancel the default behavior of an event, You need to use
event.preventDefault
.A shorter version of @AnishChittora code is :