HTML Forms
A form is how a page asks visitors for information. Names, email addresses, choices between options, it all goes through forms. The main tag is form, and everything a visitor types or selects sits inside it. When the visitor submits, the browser packages the data and sends it on its way.
Each piece of input has its own tag. The input tag creates single-line fields, and its type attribute decides what kind. type="text" makes a plain box, type="checkbox" makes a box to tick, and type="email" checks that the value looks like an address. Every field should sit next to a label that says what it is for.
Two details decide whether a form works. Every field that should send data needs a name attribute; without one, the value is collected and then dropped. And every field needs a label tied to it, so screen readers can announce it and clicking the label focuses the field. Skip either and the form quietly fails someone.
Linking labels to fields
Pair every field with a label. Give the input an id, then give the label a for attribute with the same id. Clicking the label focuses the field, which makes small checkboxes far easier to hit, and screen readers announce the label when the field is focused. Wrapping the input inside the label also works, but the for and id pair is the robust pattern.
<label for="email">Email</label>
<input type="email" id="email" name="email">
GET versus POST
The method attribute chooses how data travels. GET appends the data to the address bar, visible to anyone, which is fine for search boxes. POST sends the data in the request body, hidden from the address, which is required for passwords and large amounts of data. The default is GET, so forms that collect sensitive data must set method to post.
<form action="/search" method="get">
<input type="text" name="q">
<button type="submit">Search</button>
</form>
Syntax
<form action="/save" method="post">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<button type="submit">Send</button>
</form>
Inputs Without name="" Never Submit - And Enter Key Implicitly Submits First Button
Two silent form traps: 1) An <input> without a name attribute is excluded from form submission and FormData - data just vanishes, no error. 2) Pressing Enter in any text input triggers the first submit button in tree order (HTML5 4.10.21.2), not the visible 'Save' button. Stack Overflow #925334 (88↑) shows multi-button forms submitting wrong action.
<input name="email" required autocomplete="email"> // name required
<input type="hidden" name="action" value="save">
Good to know
- The form tag wraps every field and the submit button.
- The type attribute decides what each input looks like.
- Only fields with a name attribute get sent.
- Use GET for searches and POST for data that should stay out of the URL.