Sub topic 1
Anatomy of a form: form, action, and method
Prerequisites
This chapter assumes you can read basic HTML: elements, attributes, and nesting. You should know how to open a page in a browser and use its developer tools, especially the Network panel. No JavaScript is needed here. Later chapters cover scripting.
What a form element does
A <form> element groups controls (inputs, selects, buttons) and tells the browser what to do with their values when the user submits. The form does not send anything by itself. The browser reads the form's attributes, collects the values from the controls inside it, builds an HTTP request, and navigates to the response.
Here is the minimal form that the rest of this chapter takes apart.
<form action="/subscribe" method="post">
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required>
<button type="submit">Subscribe</button>
</form>Three parts matter here:
actionsays where the request goes.methodsays which kind of request to make.- The controls inside the form supply the data. The
nameattribute on each control decides whether and how its value is sent. A later chapter covers names and values in detail.
What happens on submit
When the user clicks the submit button or presses Enter in a text field, the browser runs these steps:
- It checks built-in validation. If any control is invalid, it stops and shows a message.
- It gathers the name and value pair of every successful control. A successful control has a
name, is not disabled, and, for checkboxes and radios, is checked. - It encodes the pairs according to the form's encoding type.
- It sends the request to the
actionURL using themethod. - It replaces the current page with the response, unless a
targetor script changes that.
For the example above, the browser sends a request like this:
POST /subscribe HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
email=ada%40example.comThe @ becomes %40 because the body uses URL encoding. You can see this request in the Network panel after you submit.
The action attribute
action holds a URL. The browser resolves it against the page's address like any other link.
| Value on page `https://example.com/blog/post` | Request goes to |
|---|---|
| `action="/subscribe"` | `https://example.com/subscribe` |
| `action="subscribe"` | `https://example.com/blog/subscribe` |
| `action="https://api.example.org/join"` | `https://api.example.org/join` |
| `action=""` or no `action` | `https://example.com/blog/post` |
Without an action, the form submits to the URL of the current document. That is handy for a page that both shows and processes a form, but it is easy to do by accident. Write the action explicitly so the target is visible in the markup.
A form can submit to another origin. The browser does not block this for ordinary form submissions, which is why servers must protect state-changing endpoints against cross-site request forgery. The action URL is not a security boundary.
The method attribute
method accepts three values.
| Value | Behavior |
|---|---|
| `get` | Puts the encoded pairs in the URL query string. This is the default. |
| `post` | Puts the encoded pairs in the request body. |
| `dialog` | Sends nothing. It closes the `<dialog>` that contains the form. |
Values are case-insensitive. Any missing or unrecognized value falls back to get, so a typo such as method="psot" silently sends a GET request.
A search form is the classic use of GET:
<form action="/search" method="get">
<label for="q">Search</label>
<input id="q" name="q" type="search">
<button type="submit">Go</button>
</form>Typing forms and submitting navigates to /search?q=forms. The result can be bookmarked and shared. For GET, the browser replaces any query string already written in action. If you write action="/search?lang=en", the lang part is dropped. Put such values in a hidden input instead.
The next chapters cover GET versus POST in depth. For now, use this rule: GET for requests that only read data and are safe to repeat, POST for anything that creates or changes data.
Other form attributes worth knowing
You will use these less often than action and method.
enctypesets how a POST body is encoded. The default isapplication/x-www-form-urlencoded. File uploads needmultipart/form-data. The file upload chapter covers this.targetchooses where the response appears, for example_blankfor a new tab.novalidateturns off built-in validation on submit. It is useful when you run your own validation.autocomplete="off"on the form sets the default for all its controls. Per-control hints are covered in a later chapter.namelets scripts reach the form asdocument.forms.signup.
A submit button can override some of these for one submission with formaction, formmethod, formenctype, formtarget, and formnovalidate:
<form action="/articles/42" method="post">
<label for="title">Title</label>
<input id="title" name="title" type="text">
<button type="submit">Publish</button>
<button type="submit" formaction="/articles/42/draft">Save draft</button>
</form>Both buttons send the same fields. The second one sends them to a different URL.
Which controls belong to a form
Normally a control belongs to the form that contains it. Nesting forms is invalid. The HTML parser ignores a nested <form> start tag, so the inner controls end up in the outer form.
You can attach a control to a form from anywhere on the page by giving the form an id and the control a form attribute:
<form id="filters" action="/products" method="get">
<label for="color">Color</label>
<input id="color" name="color" type="text">
<button type="submit">Filter</button>
</form>
<label for="sort">Sort by</label>
<select id="sort" name="sort" form="filters">
<option value="price">Price</option>
<option value="name">Name</option>
</select>The select sits outside the <form> element but still submits with it. This is useful for table layouts and toolbars where the markup structure forbids wrapping the controls.
Common mistakes
- Missing
name. A control without anameis never submitted, so the field looks fine but the server never sees it. - No submit button. A form with several text fields and no submit button may not submit on Enter. Always include
<button type="submit">. - Unwanted page reloads. A form handled entirely by JavaScript still navigates unless the script calls
preventDefault()on thesubmitevent. - Wrong method for the job. A GET form that changes data can be triggered by link prefetching, repeated by the back button, and logged with its values.
- Query string in
actionwith GET. The browser discards it, as described above. - Nested forms. Use the
formattribute orformactioninstead.
Exercises
Exercise
A page at https://example.com/shop/cart contains <form action="pay" method="post">. Which URL receives the request, and what happens if you change method to "POST " with a trailing space?
Show answer
The request goes to https://example.com/shop/pay, because a relative action resolves against the directory of the current page. Method values are case-insensitive, but a trailing space is not trimmed. "POST " is not a valid value, so the browser falls back to the default and sends a GET request.
Exercise
You write <form action="/search?lang=en" method="get"> with a text input named q. The user types html. What URL does the browser request, and how do you keep lang=en?
Show answer
The browser requests /search?q=html. For GET it replaces the query string in action, so lang=en is lost. To keep it, add <input type="hidden" name="lang" value="en"> inside the form. The request then becomes /search?q=html&lang=en.