0
0
HtmlHow-ToBeginner · 3 min read

How to Create Radio Button in HTML: Simple Guide

To create a radio button in HTML, use the <input> element with type="radio". Group radio buttons by giving them the same name attribute so only one can be selected at a time.
📐

Syntax

The basic syntax for a radio button uses the <input> tag with type="radio". The name attribute groups buttons so only one can be selected. The value attribute holds the value sent when the form is submitted.

  • type="radio": defines the input as a radio button.
  • name: groups radio buttons together.
  • value: the value assigned to this option.
  • id and label: connect label text to the button for accessibility.
html
<input type="radio" name="group1" value="option1" id="option1">
<label for="option1">Option 1</label>
Output
A single radio button labeled 'Option 1' that can be selected.
💻

Example

This example shows a group of radio buttons where only one option can be selected at a time. Labels are clickable for better usability.

html
<form>
  <input type="radio" id="red" name="color" value="red">
  <label for="red">Red</label><br>
  <input type="radio" id="green" name="color" value="green">
  <label for="green">Green</label><br>
  <input type="radio" id="blue" name="color" value="blue">
  <label for="blue">Blue</label>
</form>
Output
Three radio buttons labeled Red, Green, and Blue where only one can be selected.
⚠️

Common Pitfalls

Common mistakes include:

  • Not using the same name attribute for related radio buttons, which allows multiple selections.
  • Missing label tags, which hurts accessibility and usability.
  • Not associating label with input using for and id.
html
<!-- Wrong: Different names allow multiple selections -->
<input type="radio" name="choice1" value="a"> A<br>
<input type="radio" name="choice2" value="b"> B<br>

<!-- Right: Same name groups buttons -->
<input type="radio" name="choice" value="a" id="a">
<label for="a">A</label><br>
<input type="radio" name="choice" value="b" id="b">
<label for="b">B</label>
Output
Two sets of radio buttons: first set allows multiple selections, second set allows only one selection.
📊

Quick Reference

AttributeDescriptionExample
typeDefines input as radio buttontype="radio"
nameGroups radio buttons to allow single selectionname="group1"
valueValue sent when selectedvalue="option1"
idUnique identifier for inputid="option1"
label (for)Text label linked to input

Key Takeaways

Use type="radio" on <input> to create radio buttons.
Group related radio buttons with the same name attribute to allow only one selection.
Always use <label> with for attribute for better accessibility and usability.
Avoid giving different name values to radio buttons that should be grouped.
The value attribute defines what is sent when the form is submitted.