How to submit a form using jQuery.

This is a short tutorial on how to submit a HTML form using the jQuery library. As you probably already know, jQuery is a JavaScript library that comes packed with a wide range of useful features. One of those handy “features” that we can use in this case is the .submit() method.

Take a look at the following example, which includes a sample HTML form:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JQuery Form Submission Example</title>
    </head>
    <body>

        <!-- Our example form -->
        <form action="submit.php" id="example_form">
            <label>
                Your Email Address:
                <input type="text" name="email_address">
            </label>
            <br>
            <button type="button" id="submit_form">Submit</button>
        </form>

        <!-- Include JQuery -->
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script>
            //When the document is ready.
            $(document).ready(function(){
                //Attach a CLICK event handler to our #submit_form button.
                $("#submit_form").click(function(){
                    //If the user clicks on the button, then submit
                    //the form.
                    $("#example_form").submit();
                });
            });
        </script>

    </body>
</html>

In the example above, you can see the following:

  1. We have a HTML form with the ID “example_form“.
  2. Inside that form, we have a button element with the ID “submit_form“.

The ID attribute is extremely important in this case as it allows us to easily access the element using jQuery.

In our JavaScript code, we did the following:

  1. We wrapped all of our code inside the $( document ).ready() method. This ensures that our JavaScript code is not executed until the jQuery library has loaded and the DOM is ready.
  2. Inside our ready method, we attached a “click” event listener to our “submit_form” button. This event listener will “listen” for any clicks on our button.
  3. If our listener detects that the “submit_form” button has been clicked, it will call the submit() method on our “example_form” form. This essentially triggers the submit event on our HTML form.

If you run the example above, you should see that the form submits and that it attempts to redirect to a URL at submit.php