The Wayback Machine - https://web.archive.org/web/20240927065530/https://www.geeksforgeeks.org/how-to-prevent-buttons-from-submitting-forms-in-html/
Open In App

How to Prevent Buttons from Submitting Forms in HTML?

Last Updated : 14 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We will use different approaches for preventing buttons from submitting forms. There are several reasons where preventing the buttons from submitting forms, i.e., if the user hasn’t completed all the required form fields, or added incorrect details in the form, etc.

Below are the approaches to prevent buttons from submitting forms in HTML:

Approach 1: Disable the submit button

We can stop the submit button from submitting the form by disabling it. This means you can’t click on the button as it is non-clickable by using the ‘disabled’ property. We are going to use the disabled attribute to do this.

Syntax:

<form>
<button type="submit" disabled>Submit</button>
</form>

Example: In the following example, we are adding the disabled attribute to it so it can’t be clicked and hence the form will not be submitted.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Disable Submit Button</title>
    <style>
        form {
            margin: 300px 500px;
            display: flex;
            flex-direction: column;
            text-align: center;
        }

        h1 {
            color: green;
        }
    </style>
</head>

<body>
    <form>
        <h1>GeeksforGeeks</h1>
        <label for="name">Name:</label>
        <input type="text" 
               id="name" 
               name="name" />
        <br />
        <label for="email">Email:</label>
        <input type="email" 
               id="email" 
               name="email" />
        <br />
        <button type="submit" disabled>
              Submit
        </button>
    </form>
</body>

</html>

Output:

Approach 2: Using the onsubmit Method

To prevent buttons from submitting forms in HTML use the onsubmit attribute with return false value.

Example: In the following example, we are adding the onsubmit attribute with return false and hence the form will not be submitted.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Disable Submit Button</title>
    <style>
        form {
            margin: 300px 500px;
            display: flex;
            flex-direction: column;
            text-align: center;
        }

        h1 {
            color: green;
        }
    </style>
</head>

<body>
    <form onsubmit="return false;">
        <h1>GeeksforGeeks</h1>
        <label for="name">Name:</label>
        <input type="text" id="name" 
               name="name" />
        <br />
        <label for="email">Email:</label>
        <input type="email" id="email" 
               name="email" />
        <br />
        <button type="submit">
            Submit
        </button>
    </form>
</body>

</html>

Output:

Approach 3: Using event.preventDefault() Method

You can prevent the form submission by calling event.preventDefault() method on the submit event of the form in JavaScript. This method will stop the default form submission behavior and you can handle the form data as per your requirement.

Syntax:

document.getElementById('submit-btn').addEventListener('click', 
function(event) {

// Handle the form data
event.preventDefault();
});

Example: In this example, we get the form element using document.querySelector() and add an event listener to the submit button using addEventListener(). In the event listener function, we’re calling event.preventDefault() method to prevent the default behavior of the button, which is to submit the form. You can then handle the form data as per your requirement.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Disable Submit Button</title>
    <style>
        form {
            margin: 300px 500px;
            display: flex;
            flex-direction: column;
            text-align: center;
        }

        h1 {
            color: green;
        }
    </style>
</head>

<body>
    <form>
        <h1>GeeksforGeeks</h1>
        <label for="name">Name:
          </label>
        <input type="text" 
               id="name" 
               name="name" />
        <br />
        <label for="email">Email:
          </label>
        <input type="email"
               id="email" 
               name="email" />
        <br />
        <button type="submit" 
                id="submit-btn">Submit
          </button>
    </form>
  
    <script>
        const form = document.querySelector("form");

        // Prevent form submission on button click
        document
            .getElementById("submit-btn")
            .addEventListener("click", function (event) {
                event.preventDefault();
            });
    </script>
</body>

</html>

Output:



Previous Article
Next Article

Similar Reads

How to Prevent Users From Submitting a Form by Hitting Enter in JavaScript ?
In this article, we will see how to prevent users from submitting a form by hitting Enter button in JavaScript. Most of the time, we are required to fill out forms of different types and submit them. While submitting a form, either we press the ENTER key or press the SUBMIT button displayed on the screen. If we have to make a customized form where
3 min read
Explain the process of submitting forms and handling form submissions in Redux
Redux is a state management library for React applications. It helps you manage the state of your application in a centralized way. It provides a way to store and manage the state of your application in a single object called the store. In this article, we will learn about How to handle form submission by using Redux. When submitting forms in Redux
5 min read
How to specify an input field must be filled out before submitting the form in HTML ?
In this article, we will specify an input field that must be filled out before submitting the form. The HTML required attribute is a Boolean attribute which is used to specify that the input element must be filled out before submitting the form. This attribute works with other types of input like radio, checkbox, number, text, etc. Syntax: <inpu
1 min read
How to hide credential information form URL while submitting the HTML Form?
In this article, we are going to learn how to hide the credential information in the URL while submitting the HTML Form. POST method is used for hiding the credential information. It gets the data from the fields of the HTML form and submits it via the HTTP header without being displayed in the URL. Suppose, If a user enters the credentials as user
2 min read
How to prevent sticky hover effects for buttons on touch devices ?
When we add a hover effect to an element in CSS, it sticks in touch devices. In this article, we will learn how to solve this issue. There are two possible approaches to solve this problem - Without Using JavaScript: It can be solved by using a media query in CSS. The condition 'hover: hover' refers to the devices that support hover. Using media qu
2 min read
How to perform jQuery Callback after submitting the form ?
The after-form-submit is the set of code that is executed after a submit button is fired. Usually, it is used to blank out the form, once the submit is given. For Example, When the login credentials are wrong, the input becomes blank in the form. Approach: First, the elements in a form must be ensured if it is loaded. Then, the submit method is add
2 min read
How to specify the response page after submitting the form using HTML5 ?
In this article, we will specify the response page after submitting the form by using the action attribute in the <form> element in the document. This property is used to specify the URL page or destination of the form data that to be sent to the server after submission of the form. It can be used in the "form" element. Syntax: <form actio
1 min read
How to specify that the user is required to select a value before submitting the form in HTML5 ?
The purpose of this article is to specify that the user is required to select a value before submitting the form in HTML5. This will force the user to enter a value before a form is submitted. The <select> required attribute can be used for this purpose. It is a boolean attribute that states an input field must be filled in before the form ca
2 min read
How to specify how form-data should be encoded when submitting to server ?
HTML form provides three methods of encoding. application/x-www-form-urlencodedmultipart/form-datatext/plain 1.application/x-www-form-urlencoded: This is the default method that is applied if nothing is specified. In this method spaces are converted to the '+' symbol and special characters are converted to ASCII HEX value, and all other characters
2 min read
How to specify the form-data should be encoded when submitting it to the server in HTML5?
In this article, we will specify the form-data should encoding when submitting it to the server by using the enctype attribute in the <form> element in the HTML document. This property specifies the data that will be present in the form that should be encoded when submitting to the server. This property is used to save sensitive user data fro
1 min read
Bootstrap 5 Buttons Block buttons
Bootstrap 5 Block buttons are used to display the full-width responsive buttons. To make the block buttons, we will use .d-grid, and .d-flex classes. We can also use screen sizes classes to change the button sizes on different screen sizes. Block buttons used Classes: .d-flex: This class is used to display an element as a block-level flex container
2 min read
Foundation CSS Forms Inline Labels and Buttons
Foundation CSS is an open-source & responsive front-end framework built by ZURB foundation in September 2011, that makes it easy to design beautiful responsive websites, apps, and emails that look amazing & can be accessible to any device. It is used by many companies such as Facebook, eBay, Mozilla, Adobe, and even Disney. The framework is
3 min read
Spectre Forms Horizontal forms
Spectre Forms Horizontal forms are horizontal forms if you want to create a horizontal form then you have to use the form-horizontal class in form element. For each fields in the form you can use col-* and col-xs/sm/lg/xl-* class to the child elements for responsive form row layout. Here the * can be replaceable by 1 to 12 any number you want based
2 min read
Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
Reactive Forms vs Template Driven Forms
Angular provides two main approaches for handling forms: Reactive Forms and Template-Driven Forms. In this article, we'll learn more about Reactive Forms and Template-Driven Forms in detail. Table of Content Reactive FormsTemplate Driven FormsDifference between Reactive Forms and Template Driven FormsConclusionReactive FormsReactive Forms is a way
6 min read
How to prevent XSS with HTML/PHP ?
Cross-Site Scripting or XSS is a type of security vulnerability where an attacker gains access to a website and executes a potentially malicious script at the client's side. This is one of the code injections attacks which can be caused by incorrectly validating user data, which usually gets inserted into the page through a web form or using a hype
4 min read
How to Prevent the Display of “Getting Framed" in HTML ?
When you create a website, you want to ensure that your content is displayed in a safe and secure manner. One potential security vulnerability that you may face is the risk of your website being embedded in an iframe, also known as "getting framed". An iframe is an HTML element that allows you to embed another website within your own page. While if
4 min read
How to prevent browser to remember password in HTML ?
Browsers remember information submitted through `<input>` fields, suggesting previously entered values on subsequent visits. This can create security issues. There are several methods to prevent browsers from remembering passwords in HTML which are as follows: Table of Content Using autocomplete attributeBy Deleting cookiesUsing autocomplete=
3 min read
HTML | DOM MouseEvent buttons Property
The buttons property of mouse event is used to return a number. The number indicates which mouse button or mouse buttons were pressed when a mouse event was triggered. This property is usually used along with the onmousedown event. This property is read-only. Due to lack of browser support, you may want to look at the button property instead. Synta
2 min read
How to Create Text Reveal Effect for Buttons using HTML and CSS ?
Buttons are the most important user interface component for any website. It is very important to design the buttons in a creatively unique way. The text-reveal effect for a button is used when it is used to reveal some offer or exciting content for enhancing the user experience. Approach: The approach is to cover the button with a strip of the same
2 min read
How to add Radio Buttons in form using HTML ?
In this article, we will learn how to add Radio Buttons in form using HTML. We know that Radio Buttons are used to select only one option out of several options. It is generally used in HTML form. If we want to deselect any option we have to select another option in the case of a radio button. Approach: To add a radio buttons in a webpage, the HTML
1 min read
How to create a form with custom buttons in HTML ?
HTML form contains other form elements like text box, check box, radio button, submit button, and many more. For creating an HTML form, <form>________</form>tag is used as it is paired tag so starting and closing tags both are required. Other form elements are placed within these tags. It can be placed anywhere in the body tag of an HTM
3 min read
How to use multiple submit buttons in an HTML form ?
Every HTML form deals with the server side with an action attribute. The HTML action Attribute is used to specify where the form data is to be sent to the server after submission of the form. As the destination of our data is stored in the action attribute each and every button will lead us to the same location. To overcome this difficulty we have
2 min read
How To Use Images As Buttons In HTML ?
Ever seen a website with a cool image that, when clicked, performs an action like submitting a form? That's what happens when you use images as buttons in HTML. Images can be used as interactive buttons in HTML, offering a visually appealing way to enhance user interfaces. For In this article, we will explore various approaches to implementing imag
3 min read
How to prevent parents of floated elements from collapsing in CSS?
It is known that HTML elements like div, paragraphs, texts, etc. grow to fit the content of their child. But if the child of those elements is floated either to the right or left then the parents may collapse. That is, they will lose their actual behavior. Let's understand this with an example: Consider the below code. In the below program, a paren
4 min read
How to prevent line breaks in the list of items using CSS?
The display:inline-block property is used to show an element in the inline-level block container. It converts the block of elements into an inline element. Use height and width property to set an inline element. The display property is used to prevent a line break of a list of items. Syntax: element { display:inline-block;} Example: C/C++ Code <
1 min read
How to prevent column break within an element?
We can prevent column break within an element by using a CSS break-inside Property. The break-inside property in CSS is used to specify how the column breaks inside the element. Sometimes content of an element is stuck between the column. To prevent column break we should use the break-inside Property set to avoid. Syntax: column-break-inside:avoid
1 min read
How to prevent inline-block divs from wrapping ?
The display: inline-block; is a layout property in CSS that does not add a line break after the element. As a result, the elements can sit next to each other. The major difference between display: inline; and display: inline-block; is that, display: inline-block; also allows us to set the width and height of the element. We can prevent inline-block
5 min read
Prevent System from Entering Sleep mode in ElectronJS
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. In some desktop applications, a need arises due to
6 min read
How to prevent overriding using fake namespace in JavaScript ?
Overriding is basically when you define multiple functions or variables that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed. Overriding usually happens when you have multiple javascript files in your page. It can be an external
2 min read