อ็อบเจกต์ Label แทนอีลีเมนต์ <label> ใน HTML DOM ใช้เชื่อมโยงป้ายกำกับกับช่องกรอกข้อมูล
ไวยากรณ์ (Syntax)
var labelObject = document.createElement("LABEL")
คุณสมบัติ
| คุณสมบัติ | คำอธิบาย |
|---|---|
| control | คืนค่าการควบคุม (control) ของ label (อีลีเมนต์ที่เชื่อมโยง) |
| form | คืนค่าการอ้างอิงถึงฟอร์มที่ครอบคลุม label นี้ |
| htmlFor | อ่าน/ตั้งค่าค่าแอตทริบิวต์ for ของ label |
ตัวอย่างการใช้งาน (คุณสมบัติ htmlFor)
ตัวอย่างเดียวกับบทความ 1004064723 - เปลี่ยนการเชื่อมโยง label ระหว่าง editorOne และ editorTwo
<!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">Current Editor:</label><br>
<input type="text" id="editorOne" placeholder="editorOne">
<input type="text" id="editorTwo" placeholder="editorTwo">
<input type="button" onclick="getEventData()" value="Change Editor">
<div id="divDisplay">Label for attribute set as 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 set as editor one';
labelSelect.htmlFor = 'editorOne';
}
}
</script>
</body>
</html>
ผลลัพธ์
ก่อนคลิกปุ่ม "Change Editor": Label เชื่อมกับ editorTwo
หลังคลิกปุ่ม "Change Editor": Label เปลี่ยนเชื่อมกับ editorOne
หมายเหตุ: รูปภาพตัวอย่างจากต้นฉบับไม่ได้รวมอยู่ในเนื้อหานี้