How To Remove Default Behavior of Form’s Submit Button in JS

Date Published: 21/03/2020 Published By: JaiSchool

When we click on the submit button of form or press enter. Then our form submits. There is a method in Javascript to remove this functionality of the HTML form which name is preventDefault().

preventDefault() method of Javascript can be used with two events - onclick & onsubmit.

You need to write something in function's parameter to examine the event to disable it. Here I have passed 'e' in its parameter. Then apply the preventDefault() method on 'e' in the body of the function.

Use onsubmit global keyboard event when you use preventDefault() function with form.

<!DOCTYPE html>
<html>
<head>
	<title>Remove Submit Button Default Behaviour</title>
</head>
<body>
	<form id="frm">
		<input type="text">
		<input type="Submit">
	</form>

	<script>
		var submit_form=document.getElementById("frm");
		submit_form.onsubmit=function(e)
		{
			e.preventDefault();
		}
		
	</script>
</body>
</html>

Use onclick mouse event when you want to use preventDefault() function on input[type=submit] button.

<!DOCTYPE html>
<html>
<head>
	<title>Remove Submit Button Default Behaviour</title>
</head>
<body>
	<form>
		<input type="text">
		<input type="Submit" id="sbt">
	</form>

	<script>
		var submit_btn=document.getElementById("sbt");
		submit_btn.onclick=function(e)
		{
			e.preventDefault();
		}
		
	</script>
</body>
</html>

So you may be thinking, why and when I need to disable the default behavior of the submit button?

Basically, when you do ajax request to a PHP page to send form data then you need to use this.

Other Reading
|| Intro to SQL
|| Create a database in SQL
|| Create a table in SQL
|| Insert data in a table
|| Print array length in PHP
|| String length in PHP
|| Print an array in PHP
|| Convert array to a string in PHP

I hope, you have understood how to disable submit action. Now, you can prevent any buttons from submitting forms with the help of Javascript.

Publish A Comment

Leave a Reply

Your email address will not be published. Required fields are marked *