How to render a form with an external submit button

How to render a form with an external submit button

·

2 min read

There should be at least two ways for any user to submit a form. Pointer users should be able to press a submit button, and keyboard users should be able to press the enter key. Both of these UX behaviors are provided natively by the browser, given a button with type="submit" (or an input with type="submit") is rendered somewhere inside a form tag.

<form>
  <input name="name" />
  <input name="surname" />

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

Unfortunately, it's not always possible to render the submit button inside the form element. This is especially true if you don't have complete control over the DOM structure, like when using a component library. So you may end up with something like:

<form>
  <input name="name" />
  <input name="surname" />
</form>

...

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

And then quickly see that neither clicking the submit button nor pressing the enter key submit the form.

form attribute

No worries! While submit buttons automatically associate with an ancestor form, it's possible to explicitly link a submit button with another form using the form attribute. There are just two requirements:

  1. a unique id must be assigned to the form element

  2. a form attribute must be added to the button with the value of the form's id.

<form id="nameForm">
  <input name="name" />
  <input name="surname" />
</form>

...

<button type="submit" form="nameForm">
  Submit the form
</button>

But wait!

The form will now submit when pressing the submit button, but pressing the enter key still won't work. This is because the browser still requires a submit button or input to be rendered somewhere inside the form for it to automatically handle form submission when the user presses the enter key. The easiest way to fix this is to render another submit button inside the form and then hide it visually with CSS.

<form id="nameForm">
  <input name="name" />
  <input name="surname" />
  <button type="submit" style="display: none;" />
</form>

...

<button type="submit" form="nameForm">
  Submit the form
</button>

Now the form is accessible and you should be able to render that real submit button wherever you need to.