Skip to content

JavaScript onsubmit preventDefault

  • by

Using the preventDefault() method to onsubmit event prevents the default form action for Ajax form submissions. The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

JavaScript onsubmit preventDefault

Simple example code submit event fires whenever the user submits a form.

<!DOCTYPE html>
    <p>Choose your preferred contact method:</p>
      <input type="radio" id="email" name="contact" value="email">
      <label for="email">Email</label>

      <input type="radio" id="phone" name="contact" value="phone">
      <label for="phone">Phone</label>
      <button id="submit" type="submit">Submit</button>

    $(document).ready(function() {
      $('form').submit(function(e) {
        // or return false;


JavaScript onsubmit preventDefault

You can use an inline event onsubmit like this

<form onsubmit="alert('stop submit'); return false;" >

Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event:

const element = document.querySelector('form');
element.addEventListener('submit', event => {
  // actual logic, e.g. validate the form
  console.log('Form submission cancelled.');
  <button type="submit">Submit</button>

Do comment if you have any doubts or suggestions on this Js submit form topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading