javascript

Show confirmation alert before submitting a form in Javascript

In this post, we will learn how to show a confirmation alert before submitting a form in Javascript. This is a great way to avoid accidental submissions and preserve data integrity.

document.getElementById("my_form").addEventListener("submit", function() {
   if (confirm("Are you sure to submit")) {
      return true;
   } else {
      return false;
   }
});

By adding a few lines of code, you can ensure that your users confirm their submission before the form is actually submitted. In the above code example,

  1. We have created a form and added an Event Listener to it on the form submit.
  2. When the user submits the form, we are showing an alert box or confirmation box. That will have a message that you passed in the confirm() function as a parameter. Also, there will be two buttons in the alert box - cancel and ok.
  3. If you press the cancel button you can use return false to not to submit the form.

The minimal code that can be used to show the confirmation box before the form submits is as below.

if (confirm("Are you sure to submit")) {
   return true;
} else {
   return false;
}

If you are using jQuery, you can use the below code

$("my_form_id").submit(function() {
    if (confirm("Are you sure to delete it")) {
        return true;
    } else {
        return false;
    }
});
Was this helpful?