Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

HTML DOM Input Hidden value Property: ค่าของ hidden field

คุณสมบัติ valueของ hidden input คืนค่าและกำหนดเนื้อหาของแอตทริบิวต์ value ใช้เก็บข้อมูลที่ส่งไปกับฟอร์มแต่ไม่แสดงให้ผู้ใช้เห็น

รูปแบบ (Syntax)

อ่านค่า:

object.value

กำหนดค่า:

object.value = "text"

ตัวอย่างการใช้งาน

เปลี่ยนค่า hidden field และแสดงผล:

<!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; cursor: pointer; }
        .show { color: #fff; font-size: 1.2rem; font-weight: 600; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง Hidden value Property</h1>
    ช่อง hidden: <input type="hidden" class="input-field" value="Hi! I was previous value of hidden input">
    <button onclick="getType()" class="btn">คลิกเพื่อเปลี่ยนค่า</button>
    <div class="show"></div>
    <script>
        function getType() {
            var inputField = document.querySelector(".input-field");
            var msgDiv = document.querySelector(".show");
            msgDiv.innerHTML = "" + inputField.value + "";
            inputField.value = "Hello! I'm new value of hidden input";
            msgDiv.innerHTML += "" + inputField.value + "";
        }
    </script>
</body>
</html>

การใช้งานจริง

  • เก็บ CSRF token สำหรับความปลอดภัยฟอร์ม
  • เก็บ ID ของ record ที่กำลังแก้ไข
  • ส่งค่าคงที่หรือค่าที่คำนวณได้จาก JavaScript
  • ติดตามสถานะ multi-step form

การอ่านค่าในฝั่งเซิร์ฟเวอร์

PHP: $_POST['field_name'] หรือ $_GET['field_name']

Node.js (Express): req.body.field_name

Python (Flask): request.form['field_name']