How To Use Multiple Submit Buttons In An HTML5 Form (No Javascript)

How To Use Multiple Submit Buttons In An HTML5 Form (No Javascript)

·

2 min read

HTML form element makes it easy to take an action when a button is clicked through its `action` attribute. However, if you have tried to create a multi-button form that takes specific actions based on which button is clicked, you would have realized that things don't work as you'd want them to work i.e. clicking any button leads to the same action that is defined in the form element's action attribute. You can counter this situation by using Javascript. That is what people used to do before HTML5 (many still do), but HTML5 has given us a native attribute for button and input elements, which makes using multiple submit buttons in a form much easier.

The Formaction Attribute

The formaction (pronounced: form action) attribute is used in HTML5 forms to specify the URL of the page that will handle the form data when submitted. This attribute is used in conjunction with the element's type attribute, which is set to "submit" or "image". The formaction attribute overrides the action attribute of the form element, allowing for specific actions to be taken based on the button that was clicked.

For example, consider a form with three submit buttons, one labeled "Submit", one labeled "Save" and the other labeled "Delete".

<form action="/submit">
    //clicking on Submit button leads to "/submit" route
    <button type="submit">Submit</button>
    //clicking on Save button leads to "/save" route
    <button type="submit" formaction="/save">Save</button>
    //clicking on Delete button leads to "/delete" route
    <button type="submit" formaction="/delete">Delete</button> 
</form>

In the example scenario, clicking on the Submit button will trigger the default form action which is the "/submit" route. However, clicking on the Save and Delete buttons will trigger their respective routes. Notice the latter buttons have a formaction attribute that defines their action and overrides the default action of the form.

Use Image As A Submit Button

The formaction attribute can also be used with the element's type attribute set to "image", which allows for an image to be used as the submit button. In this case, the formaction attribute specifies the URL that the form data will be sent to when the image is clicked.

Compatibility

It's important to note that the formaction attribute is only supported in HTML5 and is not supported in previous versions of HTML. Additionally, the formaction attribute is not supported in some web browsers, so it's important to test your forms in multiple browsers to ensure compatibility.

Conclusion

The formaction attribute is useful for creating more dynamic and interactive forms. It allows for different actions to be taken based on which button is clicked, without the need to write javascript to manage actions, making it a valuable addition to any web developer's toolkit.