Include inputs from outside of a form on submit
Did you know that you can include input values on a form submission even if those inputs don’t live inside of the form? “Yes, of course!”, I hear you say. Did you know that you can do it without Javascript?
The form
attribute
Unbeknownst to me, HTML5 form inputs allow a special attribute called form
. If you add a value to the attribute equivalent to the ID of the form the browser will automatically include the input in the form submission.
<input type="text" name="outside" form="my-form">
<form id="my-form">
<button>Submit</button>
</form>
In this small example (demo) the text field outside
will be included in the data submitted with the form.
The form
attribute is not exclusive to inputs that have values. You could apply the attribute to a button to submit a form somewhere else on the page which could come in handy on long forms that have multiple “Save” targets. You can even have a button inside of a form that, when clicked, submits a totally separate form (demo).