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>
<html>
<body>
  <form>
    <p>Choose your preferred contact method:</p>
    <div>
      <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>
    </div>
    <div>
      <button id="submit" type="submit">Submit</button>
    </div>
  </form>

  <script>
    $(document).ready(function() {
      $('form').submit(function(e) {
        e.preventDefault();
        // or return false;
      });
    });
  </script>
</body>
</html>

Output:

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 => {
  event.preventDefault();
  // actual logic, e.g. validate the form
  console.log('Form submission cancelled.');
});
<form>
  <button type="submit">Submit</button>
</form>

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