How to Stop Submit Form in Javascript with Example

Posted on

Another article related with Javascript client-side scripting with the purpose of describing how to stop submit form in Javascript itself along with example given is written in this one. To be able to stop form from further submitting because of several reasons where one of them is because the validation process has failed is one of the purpose. In other meaning, it is not necessary to proceed further.

So, below is an example for showing how to stop submit form in javascript in the HTML web page file :

<html>
<head>
<title>
Check Submit Form
</title>
</head>
<body>
<form id="user_form" onsubmit="return ValidationEvent()">
<input type="text" id="username"></input>
<input type="text" id="password"></input>
<input type="submit" id="submit_button"></input>
</form>
</body>
</html>

The Javascript snippet code which is used for validating input type text HTML element defined in the above HTML web page must be stop at the time the validation process failed so the form submit process itself must be stop. Below the javascript snippet code mentioned shown :

<script type="text/javascript"> 
function ValidationEvent(event){ 
var username = document.getElementById("username").value; 
var password = document.getElementById("password").value;
if(document.getElementById("username").value == "") {
alert("Username cannot be empty !");
event.preventDefault();
}else if(document.getElementById("password").value == ""){
alert("Password cannot be empty !");
event.preventDefault();  
} 
</script>

The line of code which is becoming the decision on the form submit prevention is the following line of code :

event.preventDefault();

So, the above javascript method or function called ValidationEvent will be processed upon the form submission as shown in the above HTML line of code which can be shown below :

<form id="user_form" onsubmit="return ValidationEvent()">

Based on the submit event action, the method ValidationEvent will be executed and the process of validation will be started with checking the username whether it is empty or not. If it is empty the submission form will be stop and it will not going futher. It is specified by the following line of code :

if(document.getElementById("username").value == "")

The conditional if above is for checking whether or not the input type text HTML element is empty. If it is empty, it will alert for giving a message informing that the input type text HTML element is empty. Furthermore, for the process in the method named ‘ValidationEvent’ stop so it is not need to be further validated, the following line of code is written after :

event.preventDefault();

So, the process will stop and there will be no further validation process which in the above snippet code context it is for validating the password.

One thought on “How to Stop Submit Form in Javascript with Example

Leave a Reply