jQuery Prevent Default Form Submission

This article explains how to prevent the default submit action of an HTML form using jQuery. By using the event.preventDefault() method, developers can halt the standard browser behavior of reloading or redirecting the page upon submission. This technique is essential for validating form inputs on the client side, submitting data asynchronously using AJAX, or handling custom user interactions seamlessly.

The Syntax

To prevent a form from submitting in jQuery, listen for the submit event on the form element, capture the event object, and call event.preventDefault().

$('#myForm').submit(function(event) {
    event.preventDefault();
    // Your custom code or AJAX request here
});

Using the modern and flexible .on() method, the syntax is written as:

$('#myForm').on('submit', function(e) {
    e.preventDefault();
    // Your custom code or AJAX request here
});

Complete Working Example

Below is a practical implementation demonstrating an HTML form intercepted by jQuery:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Prevent Form Submit</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

    <form id="contactForm" action="/submit" method="POST">
        <label for="username">Name:</label>
        <input type="text" id="username" name="username" required>
        <button type="submit">Submit</button>
    </form>

    <div id="statusMessage"></div>

    <script>
        $(document).ready(function() {
            $('#contactForm').on('submit', function(event) {
                // Prevent standard submission
                event.preventDefault();

                // Custom logic (e.g., getting input values, AJAX)
                var nameValue = $('#username').val();
                $('#statusMessage').text('Form submission halted. Hello, ' + nameValue + '!');
            });
        });
    </script>

</body>
</html>

event.preventDefault() vs. return false

While returning false from a jQuery event handler also stops form submission, it performs two distinct actions:

  1. It calls event.preventDefault().
  2. It calls event.stopPropagation(), which stops the event from bubbling up the DOM tree.

In most scenarios, using event.preventDefault() is preferred because it explicitly targets the submission action without unexpectedly breaking event bubbling or masking errors in the surrounding code.