In this tutorial, we are going to show you how to submit an HTML form using jQuery.
As you probably already know, jQuery is a JavaScript library that comes with a wide range of useful features.
One of these handy “features” is the .submit() method, which gives us the ability to submit a form.
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:
- We have an HTML form with the ID “example_form“.
- Inside that form, there is a button element with the ID “submit_form“.
The ID attribute is extremely important in this case. This is because it allows us to easily access the element using jQuery.
In our JavaScript code, we did the following:
- We wrapped all of our code inside the $( document ).ready() method. This ensures that the browser doesn’t execute our JavaScript code until the jQuery file is loaded and the DOM is ready.
- 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 form button.
- If our listener detects that a user has clicked on our “submit_form” button, 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 jQuery submits the form and that it attempts to redirect to a URL at submit.php