HTML DOM Input Hidden Object แทนอิลิเมนต์ <input type="hidden"> ใช้สร้างและจัดการช่องซ่อนข้อมูล
รูปแบบการสร้าง (Syntax)
var hiddenInput = document.createElement("INPUT");
hiddenInput.setAttribute("type", "hidden");
คุณสมบัติหลัก (Properties)
| คุณสมบัติ | คำอธิบาย |
|---|---|
| form | คืนค่ารีเฟอร์เรนซ์ของฟอร์มที่ครอบคลุม |
| name | คืนค่าและกำหนดแอตทริบิวต์ name |
| type | คืนค่า "hidden" (อ่านอย่างเดียว) |
| defaultValue | คืนค่าและกำหนดค่าเริ่มต้น |
| value | คืนค่าและกำหนดค่าปัจจุบัน |
ตัวอย่างการใช้งาน
สลับแสดง/ซ่อน input field โดยเปลี่ยน type:
<!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; }
input { border: 1px solid #fff; background-color: transparent; color: #fff; padding: 8px; outline: none; }
input::placeholder { color: #fff; font-weight: bold; }
</style>
</head>
<body>
<h1>ตัวอย่าง DOM Input Hidden Object</h1>
<input type="text" placeholder="ใส่ชื่อของคุณ" class="input-field">
<button onclick="showHide()" class="btn">คลิกเพื่อแสดง/ซ่อนช่องกรอก</button>
<script>
function showHide() {
var inputField = document.querySelector(".input-field");
if (inputField.type === 'text') {
inputField.type = 'hidden';
} else {
inputField.type = 'text';
}
}
</script>
</body>
</html>
การใช้งานจริง
- สร้าง hidden field แบบไดนามิกเพื่อส่งข้อมูลเพิ่มเติม
- เก็บ state ของแอปพลิเคชัน (current step, filters, sorting)
- ใช้ร่วมกับ FormData สำหรับ AJAX file upload
ข้อควรระวัง
การเปลี่ยน type จาก text เป็น hidden จะทำให้ผู้ใช้ไม่สามารถโต้ตอบได้ แต่ข้อมูลยังคงอยู่ใน DOM และส่งไปกับฟอร์มได้ปกติ