คุณสมบัติ nameของ <select> คืนค่าและกำหนดแอตทริบิวต์ name ของรายการแบบเลื่อนลง ใช้เป็น key เมื่อส่งข้อมูลฟอร์ม
รูปแบบ (Syntax)
อ่านค่า:
object.name
กำหนดค่า:
object.name = "text"
ตัวอย่างการใช้งาน
แสดงค่า name attribute ของ select element:
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; color: #fff; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat; height: 100vh; }
p { font-weight: 700; font-size: 1.2rem; }
.drop-down { width: 35%; border: 2px solid #fff; font-weight: bold; padding: 8px; outline: none; }
.btn { background: #0197F6; border: none; height: 2rem; border-radius: 2px; width: 35%; margin: 2rem auto; display: block; color: #fff; outline: none; cursor: pointer; }
.show { font-size: 1.5rem; font-weight: bold; }
</style>
</head>
<body>
<h1>ตัวอย่าง Select name property</h1>
<p>สวัสดี เลือกวิชาที่ชอบ:</p>
<select class='drop-down' name="Drop Down List">
<option>Physics</option>
<option>Maths</option>
<option>Chemistry</option>
<option>English</option>
</select>
<button onclick="showName()" class="btn">แสดงชื่อ</button>
<div class="show"></div>
<script>
function showName() {
var dropDown = document.querySelector(".drop-down");
var showMsg = document.querySelector(".show");
showMsg.innerHTML = "สวัสดี! ฉันคือ " + dropDown.name;
}
</script>
</body>
</html>
ความสำคัญของ name attribute
- จำเป็นต้องมี name attribute ไม่เช่นนั้นข้อมูลจะไม่ถูกส่งไปกับฟอร์ม
- เซิร์ฟเวอร์เข้าถึงค่าที่เลือกผ่านชื่อนี้
- ควรตั้งชื่อที่อธิบายความหมายได้ (subject, category, country, ฯลฯ)
การใช้งานกับ multiple select
เมื่อใช้ multiple attribute ค่าที่ส่งจะเป็น array (หลายค่า) ภายใต้ name เดียวกัน