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

วิธีใช้ Radio Button ใน HTML Form

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

CheckboxRadio
เลือกได้หลายตัวเลือกได้ 1 ตัว
name อาจต่างกันได้name ต้องเหมือนกัน
ส่งค่าเป็น arrayส่งค่าเดียว
☑ Square⬤ Circle