What Are Radio Buttons?
Using radio inputs
We
already covered the fundamentals of radio buttons above. Let's now look
at the other common radio-button-related features and techniques you
may need to know about.
Selecting a radio button by default
To make a radio button selected by default, you include checked
attribute, as shown in this revised version of the previous example:
<form> <fieldset> <legend>Please select your preferred contact method (email is the default):</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" checked /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form>
In this case, the first radio button is now selected by default.
Note: If you put the checked
attribute on more than one radio button, later instances will override earlier ones; that is, the last checked
radio button will be the one that is selected. This is because only one
radio button in a group can ever be selected at once, and the user
agent automatically deselects others each time a new one is marked as
checked.
Providing a bigger hit area for your radio buttons
In the above examples, you may have noticed that you can select a radio button by clicking on its associated <label>
element, as well as on the radio button itself. This is a really useful
feature of HTML form labels that makes it easier for users to click the
option they want, especially on small-screen devices like smartphones.
Beyond accessibility, this is another good reason to properly set up <label>
elements on your forms.