Tap Text to Affect Checkboxes and Radio Buttons
You have encountered checkboxes and radio buttons. You tap the checkbox or the radio button to change its state.
Examples:
The checkbox can be checked or unchecked. The radio button can only be checked. To uncheck a radio button, another radio button of the same set needs to be checked.
Now, the interesting part.
The HTML label
tag can be used so you can tap the label text of the checkbox or radio button and it will act as if you tapped the box or button itself.
Examples:
The text to tap doesn't need to be right next to the box or button.
Examples:
Now, let's have a look at the code.
Here is the code for the first example (checkbox and radio buttons without tappable text)
<input type="checkbox"> Checkbox <input type="radio" name="set"> Radio Button One <input type="radio" name="set"> Radio Button Two
The above are minimum-code examples. The checkbox is not required to have a name. In order for the browser to recognize them as a set, the radio buttons need the same name.
The checkbox is checked or unchecked when it is tapped. The radio buttons are checked when tapped. When one radio button is checked, any others in the set are unchecked.
Now, let's do the code where the text labels are tappable. Tap the text label and the corresponding checkbox or radio button is affected.
<label><input type="checkbox"> Checkbox</label> <label><input type="radio" name="set"> Radio Button One</label> <label><input type="radio" name="set"> Radio Button Two</label>
The checkbox and radio button fields are enclosed in label
tags. It's that simple.
The third and last example, though, is not that simple.
In order to specify text to tap that is at a different location than the checkbox or radio buttons:
-
The
input
tag for the checkbox and radio button fields must have anid
value. -
The
label
for the tappable text must have afor
tag that matches the id of the field is supposed to affect.
<input id="cbox" type="checkbox"> Checkbox <input id="rad1" type="radio" name="set"> Radio Button Button One <input id="rad2" type="radio" name="set"> Radio Button Two <label for="rad1">→Tap to affect the first radio button</label> <label for="rad2">→Tap to affect the second radio button</label> <label for="cbox">→Tap to affect the checkbox</label>
Notice that the id
value of the checkbox and radio button input
fields match the for
value of the label
tags.
An example of how it works: When the text with <label for="cbox">
is tapped, the checkbox with <input id="cbox"…
is affected.
Now you know how to do it. When certain text is tapped, a certain checkbox or radio button is affected.
This article first appeared with an issue of the Possibilities newsletter.
Will Bontrager