Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Đối tượng Input Hidden trong HTML DOM

Đối tượng Input Hidden đại diện cho <input type="hidden"> - trường không hiển thị nhưng gửi dữ liệu kèm form. Dùng cho CSRF token, ID record, state multi-step form...

Tạo hidden input động

var hiddenInput = document.createElement("INPUT");
hiddenInput.setAttribute("type", "hidden");
hiddenInput.setAttribute("name", "token");
hiddenInput.setAttribute("value", "abc123");

Các thuộc tính chính

Thuộc tínhMô tả
formForm chứa input (chỉ đọc).
nameTên trường (key khi submit).
typeLuôn là "hidden" (chỉ đọc).
defaultValueGiá trị mặc định ban đầu.
valueGiá trị hiện tại (có thể đọc/ghi tự do).

Ví dụ: Chuyển đổi text ↔ hidden

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; background: #F19A3E; color: white; font-family: sans-serif; padding: 20px; }
        .btn {
            background-color: #3C787E; border: none; color: white;
            padding: 10px 20px; border-radius: 25px; width: 60%;
            margin: 15px auto; display: block; cursor: pointer;
        }
        input[type="text"] {
            border: 1px solid white; background: transparent; color: white;
            padding: 8px; outline: none; width: 300px;
        }
        input::placeholder { color: white; font-weight: bold; }
    </style>
</head>
<body>
    <h1>Ví dụ DOM Input Hidden Object</h1>
    <input type="text" placeholder="Nhập tên của bạn" class="input-field">
    <button onclick="toggleVisibility()" class="btn">Ẩn/Hiện trường nhập</button>
    <script>
        function toggleVisibility() {
            var input = document.querySelector(".input-field");
            if (input.type === 'text') {
                input.type = 'hidden';
            } else {
                input.type = 'text';
            }
        }
    </script>
</body>
</html>

Kết quả

Input text ban đầu:

Đối tượng Input Hidden trong HTML DOM

Sau khi nhấn "Ẩn/Hiện" - input biến mất (type=hidden):

Đối tượng Input Hidden trong HTML DOM

💡 Mẹo: Dùng type="hidden" thay vì display:none khi muốn giá trị **vẫn được submit** cùng form. Phần tử display:none vẫn submit, nhưng disabled thì **không**.