Open In App

How to use multiple submit buttons in an HTML form ?

Last Updated : 26 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Using multiple submit buttons in an HTML form allows different actions based on the button clicked. Each submit button can trigger a unique server-side or JavaScript process while sharing the same form fields, enabling various functionalities within a single form structure.

Syntax

<form action="/https/www.geeksforgeeks.org/DEFAULT_URL" method="post">
<!-- Input fields here -->

<!-- This button will post to the
/DEFAULT_URL of the form-->
<button type="submit">BUTTON 1</button>

<!-- This button will post to the custom
URL of the formaction attribute-->
<button type="submit" formaction="/URL2">
BUTTON 2
</button>
</form>

Using Multiple Submit Button

  • Create a form with the method 'post' and set the value of the action attribute to a default URL where you want to send the form data.
  • Create the input fields inside the as per your concern.
  • Create a button with the type submit. This button will trigger the default action attribute of the form and send our input data to that URL.
  • Create another button with the type submit. Also, add a 'formaction' attribute to this button and give it the value of the secondary URL where you want to send the form-data when this button is clicked.
  • The form action attribute will override the action attribute of the form and send the data to your desired location.

Example: In this example, we use two submit buttons in a single form. Each button submits the form to a different URL using the formaction attribute, allowing users to perform different actions based on which button they click.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <title>GeeksforGeeks - Multiple Submit Buttons</title>
</head>

<body>
    <form action="https://geeksforgeeks.org/" 
          method="post">
        <h1>GeeksforGeeks</h1>

        <!-- Username Input -->
        <label for="username">Username:</label><br>
        <input type="text" name="username" 
               id="username">
        <br>

        <!-- Email Input -->
        <label for="email_id">Email id:</label><br>
        <input type="text" name="email_id" 
               id="email_id">
        <br><br>

        <!-- Submit Button 1 -->
        <button type="submit" formaction="https://www.geeksforgeeks.org/" 
                name="submit_type" value="submit_1">
            Submit 1
        </button>

        <!-- Submit Button 2 -->
        <button type="submit" formaction="https://www.geeksforgeeks.org/about/" 
                name="submit_type" value="submit_2">
            Submit 2
        </button>
    </form>
</body>

</html>

Output :

pil


Similar Reads