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

Thuộc tính disabled của Input Number trong HTML DOM

Thuộc tính disabled của <input type="number"> cho phép trả về hoặc thiết lập trạng thái vô hiệu hóa (không thể nhập, tương tác). Khi disabled, input mờ đi và không gửi giá trị khi submit.

Cú pháp

Lấy giá trị:

numberInput.disabled

Thiết lập giá trị:

numberInput.disabled = true | false

Ví dụ: Bật/tắt input number

<!DOCTYPE html>
<html>
<head>
    <style>
        html, body { height: 100%; margin: 0; font-family: sans-serif; }
        body {
            text-align: center; color: white;
            background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
            background: #B39CD0;
        }
        input[type="number"] {
            width: 35%; border: 2px solid white; background: transparent;
            color: white; font-weight: bold; padding: 8px; margin: 10px auto; display: block; outline: none;
        }
        .btn {
            background: #008B74; border: none; color: white;
            padding: 10px 20px; border-radius: 4px; width: 35%;
            margin: 20px auto; display: block; cursor: pointer;
        }
        .show { font-size: 1.5rem; font-weight: bold; margin-top: 15px; }
    </style>
</head>
<body>
    <h1>Demo Input Number disabled Property</h1>
    <p>Nhập ngày sinh của bạn (1-31)</p>
    <input type="number" class="numberInput" min="1" max="31">
    <button onclick="toggleDisabled()" class="btn">Vô hiệu hóa/Kích hoạt</button>
    <div id="result" class="show"></div>
    <script>
        function toggleDisabled() {
            var input = document.querySelector(".numberInput");
            var msg = document.getElementById("result");
            msg.textContent = "";
            if (input.disabled) {
                input.disabled = false;
                msg.textContent = "Trước disabled, giờ enabled!";
            } else {
                input.disabled = true;
                msg.textContent = "Trước enabled, giờ disabled!";
            }
        }
    </script>
</body>
</html>

Kết quả

Input number bình thường:

Thuộc tính disabled của Input Number trong HTML DOM

Nhấn nút - input bị disabled (mờ):

Thuộc tính disabled của Input Number trong HTML DOM

Nhấn lại - input enabled trở lại:

Thuộc tính disabled của Input Number trong HTML DOM

⚠️ Lưu ý: Input disabled **không gửi giá trị** khi submit form. Dùng readOnly nếu cần vẫn gửi giá trị.