Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Using HTML buttons and inputs with the form, form-method and form-action attributes

The default way you would wite an HTML form would be like this:

<form action="/action_page.php" method="get" id="form1">
    <!-- your form inputs here -->
    <button type="submit">

This will submit the form to the /action_page.php via a get method. And also the submit button has to be included in the actual HTML form.

However we can have a button that submits a form in whatever place we want on the page. The association is done through the id of the form.

<form id="form1" action="/action_page.php">
    <!-- your form inputs here -->

<!-- Far away in the DOM -->
<button form="form1" formaction="/postToTwitter.php" formmethod="POST">Post Twitter</button>
<button form="form1" formaction="/sendOnSlack.php" formmethod="GET">Share on Slack</button>

One cool thing is that we can use the formmethod and the formaction attributes to send the data to multiple endpoints with different methods. See the above example.

Another advantage of the form attributes on buttons is that we have better CSS styling and control. There is no need anymore to place the button inside the actual form element so we can style things however we want.

Not just the buttons accept these attributes, but also the input elements.

It is currently supported in all modern browsers. Of course, Internet Explorer is not included in the modern browsers category šŸ˜€ .

You can read more about it here , here or here.

Home Screencasts Best of Newsletter Search X