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

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

Thuộc tính disabled của nút button 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, nút thường hiển thị mờ đi.

Cú pháp

Lấy giá trị:

buttonElement.disabled

Thiết lập giá trị:

buttonElement.disabled = true | false

Ví dụ: Tự vô hiệu hóa nút sau khi nhấn

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; font-family: sans-serif; padding: 20px; }
        .btn {
            display: block; margin: 15px auto;
            background-color: #dc3545; color: white; border: 1px solid #dc3545;
            padding: 12px; border-radius: 25px; width: 80%;
            font-weight: bold; cursor: pointer; transition: opacity 0.3s;
        }
        .btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .msg { font-weight: bold; font-size: 1.2rem; color: #ffc107; margin-top: 15px; }
    </style>
</head>
<body>
    <h1>Ví dụ disabled Property</h1>
    <input type="button" onclick="disableMe()" class="btn" value="Nhấn để vô hiệu hóa tôi">
    <div id="msg" class="msg"></div>
    <script>
        function disableMe() {
            var btn = document.querySelector(".btn");
            btn.disabled = true;
            document.getElementById("msg").textContent = "Trước tôi enabled, giờ tôi disabled!";
        }
    </script>
</body>
</html>

Kết quả

Nút ban đầu (enabled):

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

Sau khi nhấn - nút bị vô hiệu hóa (mờ đi):

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

✅ Thực hành tốt:
  • Dùng disabled để ngăn submit trùng lặp (double submit).
  • Kết hợp với loading spinner khi xử lý AJAX.
  • Phần tử disabled **không gửi giá trị** khi submit form.
  • Có thể style với CSS: :disabled { opacity: 0.6; }.