27. Radio Buttons vs Checkboxes (Radio vs Checkbox)
Choosing only one option vs choosing many options (the secret of the name attribute)
Real-life analogy
A Radio Button is like an exam Multiple Choice Question where only 1 of the 4 answers is correct. A Checkbox is like pizza toppings where you can pick onion, paneer and corn all together!
Explanation
1. Radio button (type="radio"):
- Used when you must choose only one from several options (for example Gender: Male/Female).
- Golden rule: All the radio buttons in a group must have the same
nameattribute! If the name is different, both will be selected together, which is a big bug.
2. Checkbox (type="checkbox"):
- The user can tick multiple options (Multiple Choices) at the same time (for example Hobbies: Cricket, Music, Coding).
Golden rules
- Always keep the same
name="gender"in radio buttons.
Common mistake
Writing different names in radio buttons.
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px; font-size: 13px;">
<!-- Radio Button (only 1 can be chosen) -->
<label style="font-weight: bold;">Select gender (Radio - only one):</label><br>
<label><input type="radio" name="gender" value="m" checked> Male</label>
<label><input type="radio" name="gender" value="f"> Female</label><br><br>
<!-- Checkbox (many can be chosen) -->
<label style="font-weight: bold;">Hobbies (Checkbox - more than one):</label><br>
<label><input type="checkbox" name="hobbies" value="cricket" checked> Cricket</label>
<label><input type="checkbox" name="hobbies" value="music"> Music</label>
<label><input type="checkbox" name="hobbies" value="coding" checked> Coding</label>
</body>
</html>
Quick quiz
In a group of radio buttons, how do you make sure the user can choose only one option?
- By giving all of them the same id
- By giving all of them the same name
- By giving all of them the same value
- By adding an only-one attribute
Show answer
Answer: By giving all of them the same name
When all the radio buttons have the same name, the browser treats them as one group and lets only one be ticked.