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

HTML DOM Input Hidden form Property: ระบุฟอร์มของ hidden field

คุณสมบัติ formของ hidden input คืนค่ารีเฟอร์เรนซ์ของอิลิเมนต์ <form> ที่ครอบคลุม hidden field

รูปแบบ (Syntax)

object.form

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

ระบุว่า hidden field อยู่ในฟอร์มไหน:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; background-color: #363946; color: #fff; }
        form { margin: 2.5rem auto; }
        button { background-color: #db133a; border: none; cursor: pointer; padding: 8px 16px; color: #fff; border-radius: 5px; font-size: 1.05rem; }
        .show { font-weight: bold; font-size: 1.4rem; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง form Property</h1>
    <form id="Form 1">
        <fieldset>
            <legend>Form 1</legend>
            ช่อง hidden: <input type="hidden" class="hiddenField">
        </fieldset>
    </form>
    <button onclick="identify()">ระบุฟอร์มของ hidden field</button>
    <p class="show"></p>
    <script>
        function identify() {
            var formId = document.querySelector(".hiddenField").form.id;
            document.querySelector(".show").innerHTML = "สวัสดี! ฉันมาจาก " + formId;
        }
    </script>
</body>
</html>

การใช้งานจริงของ hidden input

  • เก็บข้อมูลที่ไม่ต้องให้ผู้ใช้เห็น (CSRF token, session ID, user ID)
  • ส่งค่าคงที่ไปกับฟอร์ม
  • ติดตามสถานะหรือขั้นตอนของ wizard form

ข้อควรระวัง

ข้อมูลใน hidden field ยังมองเห็นได้ใน View Source และ Developer Tools ไม่ควรเก็บข้อมูลลับ (password, API key) ไว้ใน hidden field