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

แอตทริบิวต์ for ใน HTML

แอตทริบิวต์ for ใน HTML ผูก <label> element กับ element แรกที่สามารถตั้ง label ได้ (labelable element) ซึ่งมี id เท่ากับค่าของ for attribute

ไวยากรณ์ (Syntax)

ดึงค่า for attribute ผ่าน JavaScript:

labelObject.htmlFor

หมายเหตุ: ใน JavaScript ใช้ htmlFor (camelCase) ไม่ใช่ for เพราะ for เป็น reserved word

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
<title>Label htmlFor</title>
<style>
  form { width: 70%; margin: 0 auto; text-align: center; }
  * { padding: 2px; margin: 5px; }
  input[type="button"] { border-radius: 10px; }
</style>
</head>
<body>
<form>
  <fieldset>
    <legend>Label-htmlFor</legend>
    <label id="CurrentEditor" for="editorTwo">Editor ปัจจุบัน:</label><br>
    <input type="text" id="editorOne" placeholder="editorOne">
    <input type="text" id="editorTwo" placeholder="editorTwo">
    <input type="button" onclick="getEventData()" value="เปลี่ยน Editor">
    <div id="divDisplay">Label for attribute ตั้งเป็น editor two</div>
  </fieldset>
</form>
<script>
  var divDisplay = document.getElementById("divDisplay");
  var labelSelect = document.getElementById("CurrentEditor");
  function getEventData() {
    if (labelSelect.htmlFor === 'editorTwo') {
      divDisplay.textContent = 'Label for attribute ตั้งเป็น editor one';
      labelSelect.htmlFor = 'editorOne';
    }
  }
</script>
</body>
</html>

ผลลัพธ์

1) ก่อนกด "เปลี่ยน Editor": Label "Editor ปัจจุบัน:" ผูกกับ editorTwo (ช่องที่ 2)

2) หลังกด "เปลี่ยน Editor": Label ผูกกับ editorOne (ช่องที่ 1) และข้อความเปลี่ยนตาม

คำอธิบายโค้ด

  • Label มี id="CurrentEditor" และ for="editorTwo" เริ่มต้น
  • มี input 2 ช่อง: id="editorOne" และ id="editorTwo"
  • ปุ่ม "เปลี่ยน Editor" เรียก getEventData()
  • ฟังก์ชันตรวจสอบ labelSelect.htmlFor แล้วสลับไป editorOne

ประโยชน์ของ htmlFor/for

  • Accessibility: Screen reader อ่าน label ให้ผู้ใช้พิการสายตา
  • Usability: คลิก label = โฟกัส/ติ๊ก input ที่ผูก (พื้นที่คลิกกว้างขึ้น)
  • Dynamic control: JavaScript เปลี่ยน htmlFor ได้เพื่อผูก label กับ element ต่างๆ แบบไดนามิก

Element ที่รองรับ label (labelable elements): input (ยกเว้น type=hidden), textarea, select, meter, progress, button, output