JQuery :: How to stop form from getting submitted or how to capture the submit event?

In our previous article which was JQuery :: How to know when ajax request has completed! we discussed how we can know when a ajax request has been completed. Today we will like to discuss on how we can prevent a form from getting submitted or do its default action.

Sometimes during development you may want to stop a form from getting submitted or want to display a error message to user and ask them to rectify it before the form is submitted with filled data. This is needed to make sure right data is being added by user during form submission.

In order to stop a form from getting submitted there are 2 ways.

One way is to make sure that form does not submit until all the values are correctly entered and all the values are checked.

Second way is to make sure that form does not submit at all so you can do background processing of data on the form.

For 1st way, create a javascript file named “form_submit.js” and store it in js folder of your project. Then call the “form_submit.js” file from inside the html file by using the following:

<script type=”text/javascript” src=”js/form_submit.js”></script>

In the HTML file where form is declared put an ID for the form and name is “submitForm” like this:

<form name=”submitForm” id=”submitForm”>

Then in the javascript file just created add the following lines in them:

$(document).ready(function() {

$(“#submitForm”).submit(function(e)

{

// Do your thing…

});

});

In the above code we have asked jquery to look for the submit event on the form with ID “submitForm” so whenever user submits the form this function will be triggered and run by browser.

In the above code add the following:

$(document).ready(function() {

$(“#submitForm”).submit(function(e)

{

return false;

});

});

The return false statement will prevent the form from getting submitted until return is turned to true.

For 2d way, in which you do not want the form to be submitted at all change the above code to the following:

$(document).ready(function() {

$(“#submitForm”).submit(function(e)

{

e.preventDefault();

});

});

The above code will prevent the default operation of the form and will allow you to process the data as you want.

We will keep updating our Jquery Tips section every 4 days, please subscribe to our feed and also share our articles on Facebook and Google Plus so other’s can benefit from our insight. Please feel free to send us your comments below, on how we can improve.