Categories
JavaScript Answers

How to confirm before a form submit with JavaScript?

Spread the love

Sometimes, we want to confirm before a form submit with JavaScript.

In this article, we’ll look at how to confirm before a form submit with JavaScript.

How to confirm before a form submit with JavaScript?

To confirm before a form submit with JavaScript, we can call the confirm function.

For instance, we write:

<form>
  <input>
  <input type="submit" />
</form>

to add a form.

Then we write:

const form = document.querySelector('form')
form.onsubmit = (e) => {
  e.preventDefault()
  const confirmSubmit = confirm('Are you sure you want to submit this form?');
  if (confirmSubmit) {
    console.log('submitted')
  }
}

to select a form with querySelector.

And then we set form.onsubmit to a function that calls confirm to check show a prompt to let the user confirm whether they want to submit the form or not.

If confirmSubmit is true, then user clicked OK and we move forward with submitting the form.

Conclusion

To confirm before a form submit with JavaScript, we can call the confirm function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *