Section 18: Labels, Name, Value, Checked and Selected
Learning Objectives
- Connect labels to their controls.
- Understand id, name and value.
- Use checked for checkboxes and radio buttons.
- Use selected for dropdown options.
- Understand how controls contribute to submitted data.
1. Labels and Their Purpose
A label tells users what a control is for. It also gives users a larger clickable target when correctly associated with the control.
Explicit label association
<label for="email">Email Address</label>
<input type="email" id="email" name="email">The label's for value must match the control's id. The name attribute serves a different purpose: it identifies the submitted field.
Implicit label association
<label>
Email Address
<input type="email" name="email">
</label>Both patterns are valid. Explicit association is often easier to maintain in larger forms.
2. id vs name vs value
<input type="text" id="username" name="username" value="bikram">- id="username": identifies the element in the document and connects it to the label.
- name="username": identifies the field in submitted form data.
- value="bikram": provides the input's initial value.
For example, this control normally submits the pair username=bikram. The exact encoding depends on the submission method and form encoding.
3. Checked Checkboxes
<label>
<input type="checkbox" name="newsletter" value="yes" checked>
Subscribe to the newsletter
</label>The checked attribute marks a checkbox as initially checked. When checked, it normally submits its name and value. When unchecked, it is generally omitted from ordinary form submission.
4. Radio Buttons
<fieldset>
<legend>Preferred Contact Method</legend>
<label>
<input type="radio" name="contact_method" value="email" checked>
Email
</label>
<label>
<input type="radio" name="contact_method" value="phone">
Phone
</label>
</fieldset>Radio buttons with the same name form a group, allowing one choice within that group. The checked attribute sets the initial selection.
5. Selected Dropdown Options
<label for="city">City</label>
<select id="city" name="city">
<option value="bbsr">Bhubaneswar</option>
<option value="cuttack" selected>Cuttack</option>
<option value="puri">Puri</option>
</select>The selected attribute sets the initially selected option. If no option is explicitly selected, the browser normally selects an option according to the select element's rules.