คุณสมบัติ nameของ hidden input คืนค่าและกำหนดแอตทริบิวต์ name ใช้เป็น key เมื่อส่งข้อมูลฟอร์มไปเซิร์ฟเวอร์
รูปแบบ (Syntax)
อ่านค่า:
object.name
กำหนดค่า:
object.name = "text"
ตัวอย่างการใช้งาน
แสดงและเปลี่ยนค่า name attribute:
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; background-color: #F19A3E; color: #fff; }
.btn { background-color: #3C787E; border: none; height: 2rem; border-radius: 50px; width: 60%; margin: 1rem auto; display: block; color: #fff; outline: none; }
.show { color: #fff; font-size: 1.2rem; font-weight: 600; }
</style>
</head>
<body>
<h1>ตัวอย่าง Hidden name Property</h1>
ใส่ชื่อของคุณ: <input type="hidden" class="input-field" name="Hi_I'm_hidden_input_field">
<button onclick="getName()" class="btn">คลิกเพื่อดู name ของ hidden input</button>
<div class="show"></div>
<script>
function getName() {
var inputField = document.querySelector(".input-field");
var msgDiv = document.querySelector(".show");
msgDiv.innerHTML = inputField.name;
}
</script>
</body>
</html>
ความสำคัญของ name attribute
- จำเป็นต้องมี name attribute ไม่เช่นนั้นข้อมูลจะไม่ถูกส่งไปกับฟอร์ม
- ใช้เป็น key ในการเข้าถึงข้อมูลฝั่งเซิร์ฟเวอร์
- ควรตั้งชื่อที่อธิบายความหมายได้ชัดเจน (เช่น user_id, csrf_token, step)