คุณสมบัติ nameของ input type="number" คืนค่าและกำหนดแอตทริบิวต์ name ใช้เป็น key เมื่อส่งข้อมูลฟอร์มไปเซิร์ฟเวอร์
รูปแบบ (Syntax)
อ่านค่า:
object.name
กำหนดค่า:
object.name = "text"
ตัวอย่างการใช้งาน
แสดงค่า name attribute ของ number input:
<!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; }
input { width: 35%; border: 2px solid #fff; background-color: transparent; color: #fff; font-weight: bold; padding: 8px; }
.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>ตัวอย่าง Input number name property</h1>
<input type="number" class="numberInput" value="20102" name="I'm Number input field!! ">
<p>สวัสดี อยากดูชื่อของฉันไหม?</p>
<p>กดปุ่มด้านล่างเลย</p>
<button onclick="showName()" class="btn">แสดงชื่อ</button>
<div class="show"></div>
<script>
function showName() {
var numberInput = document.querySelector(".numberInput");
var showMsg = document.querySelector(".show");
showMsg.innerHTML = numberInput.name;
}
</script>
</body>
</html>
ความสำคัญของ name attribute
- จำเป็นต้องมี name attribute ไม่เช่นนั้นข้อมูลจะไม่ถูกส่งไปกับฟอร์ม
- เซิร์ฟเวอร์เข้าถึงค่าผ่านชื่อนี้ (เช่น
$_POST['age']ใน PHP) - ควรตั้งชื่อที่อธิบายความหมายได้ชัดเจน (age, quantity, price, year)
การใช้งานกับ FormData
var formData = new FormData(form);
var numberValue = formData.get("age"); // ใช้ name attribute