Forms and Input Elements
Collect user input with form and the many flavors of input, and connect labels correctly for accessibility.
阅读需 2 分钟
Forms are how a page collects information from a user — logins, search bars, checkout flows, contact pages.
The <form> element
<form action="/submit" method="post">
<label for="name">Name</label>
<input type="text" id="name" name="name" />
<button type="submit">Submit</button>
</form>action— where the form data is sent when submitted.method— usuallyget(data appended to the URL, fine for searches) orpost(data sent in the request body, used for anything that changes data — logins, purchases, comments).
Always pair a label with its input
<label for="email">Email address</label>
<input type="email" id="email" name="email" />The for attribute on <label> must match the id on its <input>. This does two important things: clicking the label text focuses the input (larger, easier click target — especially on mobile), and a screen reader announces the label whenever the input receives focus. An input with no associated label is effectively unlabeled for anyone using assistive technology, even if it looks fine visually.
Common input types
<input type="text" />
<input type="email" />
<input type="password" />
<input type="number" min="1" max="10" />
<input type="date" />
<input type="checkbox" />
<input type="radio" name="plan" value="basic" />
<input type="file" />Using the right type isn't just semantic — it changes real behavior: type="email" triggers email-optimized mobile keyboards and basic format validation for free; type="number" shows a numeric keypad on mobile and spinner arrows on desktop; type="date" gives you a native date picker with zero JavaScript.
Radios, checkboxes, and grouping
Radio buttons sharing the same name become a mutually exclusive group — selecting one deselects the others:
<p>Choose a plan:</p>
<label><input type="radio" name="plan" value="basic" /> Basic</label>
<label><input type="radio" name="plan" value="pro" /> Pro</label>Checkboxes don't need a shared name to behave independently — each one toggles on its own.
Select dropdowns and textareas
<label for="country">Country</label>
<select id="country" name="country">
<option value="us">United States</option>
<option value="ca">Canada</option>
</select>
<label for="bio">Bio</label>
<textarea id="bio" name="bio" rows="4"></textarea><select> is for choosing one option from a list; <textarea> is for multi-line free text, unlike a single-line <input type="text">.
Buttons
<button type="submit">Submit</button>
<button type="reset">Clear</button>
<button type="button">Just a button (does nothing by default)</button>Inside a <form>, a <button> defaults to type="submit" — if you want a button that doesn't submit the form (e.g. one wired up to a JavaScript click handler), you must explicitly set type="button".