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

แอตทริบิวต์ disabled ใน HTML: ปิดใช้งานอิลิเมนต์

แอตทริบิวต์ disabled ใน HTML คืออะไร?

แอตทริบิวต์ disabled ใช้สำห ปิดใช้งาน (Disable) อิลิเมนต์** ทำให้ไม่สามารถโต้ตอบได้: ไม่ได้รับ Focus, ไม่คลิกได้, ไม่พิมพ์ได้, ไม่ส่งค่ากับ Form Submit

อิลิเมนต์ที่รองรับ disabled

<button>, <textarea>, <optgroup>, <select>, <fieldset>, <input>, <option>

ไวยากรณ์ (Syntax)

<element disabled>
<element disabled="disabled"> <!-- XHTML style -->

เป็น Boolean Attribute

ตัวอย่าง: Disabled Input ใน Fieldset

<!DOCTYPE html>
<html>
<body>
  <h2>รายละเอียด</h2>
  <form>
    <p>ข้อมูลใหม่...</p>
    <fieldset>
      <legend>รายละเอียดใหม่:</legend>
      Player: <input type="text" disabled><br>
      Rank: <input type="number"><br>
      Email: <input type="email"><br>
      Reporting Time: <input type="time">
    </fieldset>
  </form>
</body>
</html>

ผลลัพธ์

ช่อง "Player" จะเป็นสีจาง (Grayed out) ไม่สามารถพิมพ์/คลิก/โฟกัสได้ และ **ไม่ส่งค่าเมื่อ Submit ฟอร์ม**

disabled vs readonly (สำหรับ Input/Textarea)

คุณสมบัติdisabledreadonly
แก้ไขได้ไม่ได้ไม่ได้
Focus ได้ไม่ได้ได้
คัดลอกได้ได้ได้
ส่งค่ากับ Formไม่ส่งส่งได้
รูปลักษณ์สีจาง (Default UA Style)ปกติ
ใช้กับทุก Form Controlinput, textarea, select

Disabled Fieldset

<fieldset disabled>
  <legend>ส่วนนี้ปิดใช้งานทั้งหมด</legend>
  <input type="text" name="a">
  <input type="text" name="b">
  <button>Submit</button>
</fieldset>

<fieldset disabled> จะปิดใช้งาน **ทุก Form Control ภายใน** อัตโนมัติ (ยกเว้นที่อยู่ใน <legend>)

JavaScript Control

// ตั้ง/อ่าน disabled property (Boolean)
input.disabled = true;   // ปิดใช้งาน
input.disabled = false;  // เปิดใช้งาน

if (input.disabled) { ... }