How to Prevent Form submit using JQuery with example

Posted on

This is an article which is written solely to discuss about the topic specified in the title. It is about how to prevent submit action which is triggered when a user is clicking the submit button. This event is the submit action triggered by a user clicking submit button and it can be prevented by using JQuery in the context of this article.

An example is given to give the overview of what is actually happened. In this context of article, the example is given in a web application powered by a Laravel framework. For instance, in a file representing the view which in this context it is a blade view template file where the snippet code is shown as follows :

{{ Form::open(array('url' => '/server/check_resource', 'class' => 'form-horizontal', 'id' => 'home_form'))}}
<div class="form-group">
<div class="col-md-4 col-md-offset-2">
<input type="submit" class="btn btn-default" value="Submit">
{{ Form::close()}}

The above snippet code is mainly used for defining form which is going to be used to submit every input element available inside the form. But to prevent the page itself being submitted to another page and in the end refreshing or reloading the page so eventually all the value which has already been input is reset or is wiped out, there is a need to define the JQuery snippet code to handle it. Below is the snippet code which is mainly defined to able to do the task of preventing form submit :

$("#home_form").submit(function (e) {
alert("Test !");

The most important line is the line which is repsented by this code ‘e.preventDefault();’. That line is precisely the one preventing form submission. The other part is just a JQuery snippet code declaration which is detecting the submit event action. So, if there is a submit event action which is triggered in an HTML element and in this context of article, it is an HTML Form element, the snippet code defined inside the block code of it will be processed. In the above snippet code example, the action processed is popping a window dialog with a text ‘Test’ displayed on it. After that, instead of submitting the form to an URL defined in the form action which is ‘/server/check_resource’, the form submission process is purged or cancelled.

Another example using the old fashioned HTML form definition will display the same result. Below is a standard HTML form definition  :

<form action="/server/check_resource" method="POST" class="form-horizontal" id="home_form">
<div class="form-group">
<div class="col-md-4 col-md-offset-2">
<input type="submit" class="btn btn-default" value="Lanjut">

One thought on “How to Prevent Form submit using JQuery with example

Leave a Reply