Radio Button ใช้เมื่อผู้ใช้เลือกได้ เพียง 1 ตัว จากกลุ่มตัวเลือก (Single selection) สร้างด้วย <input type="radio">
Attribute สำคัญ
| Attribute | คำอธิบาย |
type="radio" | กำหนดเป็น radio button (จำเป็น) |
name | ชื่อกลุ่ม ต้องเหมือนกันทุกตัวในกลุ่ม (จำเป็น) |
value | ค่าที่ส่งเมื่อถูกเลือก |
checked | เลือกไว้ตั้งแต่แรก (boolean) - ควรมี 1 ตัวในกลุ่ม |
disabled | ปิดการใช้งาน |
required | บังคับเลือก (ใส่ใน 1 ตัวในกลุ่มพอ) |
ตัวอย่างพื้นฐาน
<!DOCTYPE html>
<html>
<body>
<p>Gender</p>
<form>
<label><input type="radio" name="gender" value="male" checked> Male</label><br>
<label><input type="radio" name="gender" value="female"> Female</label><br>
<label><input type="radio" name="gender" value="other"> Other</label>
<button type="submit">Submit</button>
</form>
</body>
</html>
Best Practices
- name ต้องเหมือนกัน ในกลุ่มเดียวกัน (browser จะ enforce single selection)
- ห่อด้วย
<label> คลิกข้อความได้
- ควรมี
checked อยู่ 1 ตัว (default selection)
- จัดกลุ่มด้วย
<fieldset> + <legend>
- จัดเรียงแนวตั้ง (vertical) อ่านง่ายกว่าแนวนอน
การจัดกลุ่ม (Fieldset)
<fieldset>
<legend>Payment Method</legend>
<label><input type="radio" name="payment" value="credit" checked> Credit Card</label><br>
<label><input type="radio" name="payment" value="paypal"> PayPal</label><br>
<label><input type="radio" name="payment" value="bank"> Bank Transfer</label>
</fieldset>
Checkbox vs Radio
| Checkbox | Radio |
| เลือกได้หลายตัว | เลือกได้ 1 ตัว |
| name อาจต่างกันได้ | name ต้องเหมือนกัน |
| ส่งค่าเป็น array | ส่งค่าเดียว |
| ☑ Square | ⬤ Circle |