คุณสมบัติ text ของ <option> คืนค่าและกำหนดข้อความที่แสดงในรายการตัวเลือกของ <select>
รูปแบบ (Syntax)
อ่านค่า:
object.text
กำหนดค่า:
object.text = "text"
ตัวอย่างการใช้งาน
เปลี่ยนข้อความของตัวเลือก "Physics" เป็น "Applied Physics":
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; color: #fff; background: radial-gradient(circle farthest-corner at 23.1% 64.6%, rgba(129,125,254,1) 0%, rgba(111,167,254,1) 90%) no-repeat; height: 100vh; }
p { font-weight: 700; font-size: 1.1rem; }
.drop-down { display: block; width: 35%; border: 2px solid #fff; font-weight: bold; padding: 2px; margin: 1rem auto; outline: none; }
.btn { background: orange; border: none; height: 2rem; border-radius: 2px; width: 35%; margin: 2rem auto; display: block; color: #fff; font-weight: bold; outline: none; cursor: pointer; }
.show { font-size: 1.5rem; font-weight: bold; }
</style>
</head>
<body>
<h1>ตัวอย่าง DOM Option text Property</h1>
<p>สวัสดี เลือกวิชาที่ชอบ:</p>
<select class='drop-down'>
<option>Physics</option>
<option>Biology</option>
<option>Maths</option>
</select>
<button type="button" onclick="changePhysicsName()" class="btn">เปลี่ยนชื่อวิชา Physics</button>
<div class="show"></div>
<script>
function changePhysicsName() {
document.querySelector(".drop-down").options[0].text = "Applied Physics";
document.querySelector(".show").innerHTML = "ตอนนี้ Physics กลายเป็น Applied Physics แล้ว";
}
</script>
</body>
</html>
ความแตกต่างระหว่าง text และ value
| คุณสมบัติ | คำอธิบาย |
|---|---|
| text | ข้อความที่ผู้ใช้เห็นใน dropdown |
| value | ค่าที่ส่งไปเซิร์ฟเวอร์ (หากไม่ระบุ จะใช้ text แทน) |
การใช้งานจริง
- แปลภาษาตัวเลือกแบบไดนามิก
- อัปเดตข้อความตามเงื่อนไข (เช่น แสดงราคา)
- สร้างตัวเลือกแบบ dynamic จากข้อมูล API