Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

วิธีใช้ Checkbox ใน HTML Form

Checkbox ใช้เมื่อผู้ใช้สามารถเลือกได้หลายตัวพร้อมกัน (Multiple selection) สร้างด้วย <input type="checkbox">

Attribute สำคัญ

Attributeคำอธิบาย
type="checkbox"กำหนดเป็น checkbox (จำเป็น)
nameชื่อฟิลด์ ส่งไป server (checkbox ที่เลือกเท่านั้น)
valueค่าที่ส่งเมื่อถูกเลือก (default: "on")
checkedเลือกไว้ตั้งแต่แรก (boolean attribute)
disabledปิดการใช้งาน
requiredบังคับเลือกอย่างน้อย 1 (สำหรับกลุ่ม)

ตัวอย่างพื้นฐาน

<!DOCTYPE html>
<html>
<body>
  <p>Which languages you work on:</p>
  <form>
    <label><input type="checkbox" name="language" value="java"> Java</label><br>
    <label><input type="checkbox" name="language" value="php"> PHP</label><br>
    <label><input type="checkbox" name="language" value="cpp"> C++</label><br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>

Best Practices

  • ห่อด้วย <label> คลิกข้อความได้ (accessibility)
  • ใช้ name เดียวกันสำหรับกลุ่ม checkbox เดียวกัน (server ได้ array)
  • value ควรเป็นค่าที่ server เข้าใจ (slug, id)
  • จัดกลุ่มด้วย <fieldset> + <legend>

การจัดกลุ่ม (Fieldset)

<fieldset>
  <legend>Programming Languages</legend>
  <label><input type="checkbox" name="lang" value="js"> JavaScript</label>
  <label><input type="checkbox" name="lang" value="ts"> TypeScript</label>
  <label><input type="checkbox" name="lang" value="py"> Python</label>
</fieldset>

Indeterminate State (JS only)

checkbox.indeterminate = true; // สถานะ "บางส่วน" (เส้นทับในกล่อง)