Sub topic 1
Anatomy of a Form: Form, Action, and Method
An HTML form collects user input and sends it somewhere. This chapter assumes basic HTML nesting, attributes, browser use, and basic JavaScript syntax.
Prerequisites
You should know how to create an HTML document, write elements and attributes, and inspect a page in browser developer tools.
The `form`, `action`, and `method`
The form element contains controls such as inputs, text areas, and buttons. Its action attribute names the server URL that receives the data. Its method attribute chooses how the browser sends that data.
GETadds the data to the URL as a query string. Use it for searches and other safe requests that retrieve data.POSTplaces the data in the request body. Use it when creating or changing data, or when the data should not appear in the URL.
<form action="/contact" method="post">
<label for="message">Message</label>
<textarea id="message" name="message" rows="4"></textarea>
<button type="submit">Send message</button>
</form>The browser sends the value of each successful control whose name attribute is present. The server receives name–value pairs such as message=Hello.
Text inputs and textarea
Use input for short, single-line values. Use textarea for longer, multiline text. Both need a name to contribute data during submission.
<label for="email">Email address</label>
<input id="email" name="email" type="email">
<label for="bio">Short biography</label>
<textarea id="bio" name="bio" rows="5" cols="40"></textarea>The type attribute describes the expected input. For example, email gives browsers useful validation and an appropriate mobile keyboard.
Labeling every control
A label gives a control an accessible name and makes its text clickable. Connect it with matching for and id values. A label can also wrap its control:
<label>
<input name="updates" type="checkbox">
Send me updates
</label>Buttons and submission
A button inside a form defaults to submission, but write type="submit" explicitly. Use type="button" for a button that should not submit the form. When submission occurs, the browser validates applicable controls, builds the form data, and sends it to action.
Exercise
Which method is usually appropriate for a search form?
Show answer
GET, because the search terms can appear in the URL and the request retrieves results.