ใช้ <fieldset> จัดกลุ่ม form controls ที่เกี่ยวข้องกัน และ <legend> ให้ชื่อกลุ่ม ช่วย accessibility และ visual grouping
โครงสร้างพื้นฐาน
<form>
<fieldset>
<legend>Group Title</legend>
<!-- form controls -->
</fieldset>
</form>
ตัวอย่าง
<!DOCTYPE html>
<html>
<body>
<form>
<fieldset>
<legend>Student Information:</legend>
<label>Student Name:<br>
<input type="text" name="sname">
</label><br>
<label>Student Subject:<br>
<input type="text" name="ssubject">
</label><br>
</fieldset>
<fieldset>
<legend>Contact Details</legend>
<label>Email:<br>
<input type="email" name="email">
</label><br>
<label>Phone:<br>
<input type="tel" name="phone">
</label>
</fieldset>
<button type="submit">Submit</button>
</form>
</body>
</html>
คุณสมบัติ
<legend>ต้องเป็น child แรกของ<fieldset>- Browser วาด border รอบ fieldset + legend เป็น label
- Screen reader จะอ่าน legend ก่อนทุก field ใน group
- สามารถ nested fieldset ได้
Attribute ของ fieldset
| Attribute | คำอธิบาย |
|---|---|
disabled | ปิดทุก control ใน group พร้อมกัน |
form | เชื่อมกับ form id อื่น (HTML5) |
name | ชื่อ group (สำหรับ JS reference) |
CSS Styling
fieldset {
border: 1px solid #ccc;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
}
legend {
font-weight: bold;
padding: 0 0.5rem;
color: #333;
}
/* Disabled fieldset */
fieldset:disabled {
opacity: 0.6;
background: #f5f5f5;
}
เมื่อไหร่ควรใช้
- ฟอร์มยาว หลาย section (Personal info, Address, Payment, Preferences)
- Radio/Checkbox groups
- Related fields ที่ validation ร่วมกัน