skip to Main Content

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


  1. 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
      }
    });
    
    Login or Signup to reply.
  2. 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:

       $(document).ready(function() {
       $('#submitButton').click(function(e) {
        e.preventDefault(); // Prevent the default form submission
    
       // Display the confirmation dialog
      if (confirm('Are you sure you want to submit the form?')) {
        // User clicked "OK" - submit the form
        $('#myForm').submit();
       } else {
       // User clicked "Cancel" - do nothing
      }
      });
     });
    
    Login or Signup to reply.
  3. When you want to cancel the default behavior of an event, You need to use event.preventDefault.

    A shorter version of @AnishChittora code is :

    const form = document.querySelector('#incidentform');
    
    form.addEventListener('onsubmit', function (e) {
      if(!confirm("Are you sure you want to submit?"))
         e.preventDefault();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search