Explain Codes LogoExplain Codes Logo

Submit form using a button outside the <form> tag

html
responsive-design
form-design
javascript
Alex KataevbyAlex Kataev·Aug 30, 2024
TLDR

Simply connect your external button to a form by using the form attribute. It takes form's id as the value:

<form id="myForm"> <!-- Spaceship control room --> <!-- Some fancy inputs and switches --> </form> <!-- Eject button dangerously outside the spaceship. Because why not? --> <button form="myForm" type="submit">Eject</button>

Upon the click on this infernal <button>, it just ejects the whole #myForm from its comfort zone. Recklessly, regardless of its safe location within <form> territory.

Extending functionality beyond basics

This is great for less complex projects - very alike to hammering a nail into wooden plank. But imagine a giant treehouse project - it involves a whole new set of tools.

Alternative triggering methods

When you need to submit your form in a little extra way, try these:

  • JavaScript: Good old vanilla JS is handy. Knock the door of your form by document.getElementById('myForm').submit();
  • jQuery: jQuery keeps it short and sweet with $('#myForm').submit();
  • Stealthy Ninja button: Sneak in a hidden submit button within the form like <input type="submit" style="display: none;" form="myForm">.

Advanced attribute usage

  • formaction: Direct your form data to a complete stranger (an alternative URL). Do so with formaction="/stranger-url".
  • method="GET": Want everyone to see your form's data in URL? Implement GET in your form method.
  • Elegant positioning: CSS styles your form for a jaw-dropping first impression.

User experience considerations

  • tabindex="0": Navigate smoothly using keyboard - it's like a walk in the park.
  • Responsive magic: Restyle your forms and buttons to be responsive, because size should not matter.

More than just Inputs - Form's friendly pals

To make a user-friendly form, you need more than just a text input.

  • input type="file": A passenger seat for files to travel.
  • Decisions, decisions: Form's own democracy with radio buttons and checkboxes.
  • JavaScript Dynamics: Add forms interactively, validate inputs, and surprise users with an all-star experience.

Prepare for Potential issues

Here are ways to bypass some asteroids on your journey:

  • Compatibility: The form attribute might give a cold shoulder to older browsers. Have an alternative approach ready.
  • JavaScript Phobia: Not every user is a JavaScript fan. Make your form usable even when JS is disabled.
  • Prevent Double submissions: Prevent the mischievous double submissions by disabling the button after the first click.