Last Updated on August 21, 2022 by Roshan Parihar
In this tutorial, learn how to submit form in jQuery and post data without page refresh. The short answer is to use the $('form').submit()
function of jQuery for form submission on button click.
You can also get the user entered values in the input boxes of the form without a page refresh using jQuery. Let’s find out with the examples given below.
Method 1: Submit Form in jQuery Using Click Event and $('form').submit()
To submit the form on button click, you have to use the jQuery selectors with $('form').submit()
function. It uses the click event of a button using the click()
function. After that, you can use the val()
function to get user input values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<script> $(document).ready(function() { $("button").click(function() { $("form").submit(); // Form submission. var name = $("#name").val(); var email = $("#email").val(); if((name == '') || (email == '')){ alert("Please fill the form"); }else{ alert("Name : " + name + "\nEmail : " + email); } }); }); </script> <form method="post"> <label>Enter Name</label> <input type="text" id="name" name="name"><br> <label>Enter Email</label> <input type="email" id="email" name="email"><br> <input type="button" name="submit" value="Submit"/> </form> |
Output
Fill the form above and click the ‘Submit’ button.
The above example contains the form with two input fields and a button for form submission. You can fill out the form and click the button for form submission to collect the form data. You will get the user-entered data in the alert message box.
Method 2: Using $("form").submit(function(){})
for Submission
In addition to the above example, you can also use the $("form").submit(function(e){})
code snippet. After that, It is also required to use the e.preventDefault()
inside the curly bracket to prevent page refresh. See the example to learn how to get the form submitted in jQuery.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<script> $(document).ready(function() { $("form").submit(function(e){ var name = $("#name").val(); var email = $("#email").val(); if((name == '') || (email == '')){ alert("Please fill the form"); }else{ alert("Name : " + name + "\nEmail : " + email); } e.preventDefault(); }); }); </script> <form method="post"> <label>Enter Name</label> <input type="text" id="name" name="name"><br> <label>Enter Email</label> <input type="text" id="email" name="email"><br> <input type="submit" name="submit" value="Submit"/> </form> |
Output
Fill the form above and click the ‘Submit’ button.
The above example contains the same button inside the form. You can fill out the form and click the button to get your entered data in an alert box.
When you submit the form without entering any data, you will get an alert message that you need to fill in the data for submission. It only allows users to submit the form when they fill all the fields of the form.
You May Also Like to Read.