Search code examples
javascriptform-submit

Javascript comfirmation message to stop form submission


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;
    }
  });

Solution

  • const form = document.querySelector('#incidentform');
    
    form.addEventListener('submit', function (event) {
      let text = "Are you sure you want to submit?";
      if (!confirm(text)) {
    event.preventDefault(); // Stops the form submission
      }
    });