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

Thuộc tính readOnly của Input Month trong HTML DOM

Thuộc tính readOnly của <input type="month"> cho phép trả về hoặc thiết lập trạng thái **chỉ đọc**. Người dùng **xem được** nhưng **không thể thay đổi** giá trị. Khác với disabled: readOnly vẫn gửi giá trị khi submit form.

Cú pháp

Lấy giá trị:

monthInput.readOnly

Thiết lập giá trị:

monthInput.readOnly = true | false

Ví dụ: Chuyển đổi ReadOnly / Read-Write

<!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;
        }
        input[type="month"] {
            display: block; width: 35%; margin: 15px auto;
            border: 2px solid white; background: transparent;
            color: white; font-weight: bold; padding: 8px;
        }
        .btn {
            background: #0197F6; border: none; color: white;
            padding: 10px 20px; border-radius: 4px; width: 35%;
            margin: 10px auto; display: block; cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Demo Input Month readOnly Property</h1>
    <p>Chọn tháng sinh của bạn?</p>
    <input type="month" class="monthInput">
    <button onclick="setReadOnly()" class="btn">Chỉ đọc (ReadOnly)&lt;/button>
    <button onclick="setReadWrite()" class="btn">Đọc & Ghi (Read/Write)&lt;/button>
    <script>
        function setReadOnly() {
            document.querySelector(".monthInput").readOnly = true;
        }
        function setReadWrite() {
            document.querySelector(".monthInput").readOnly = false;
        }
    </script>
</body>
</html>

Kết quả

Chọn tháng rồi nhấn "Chỉ đọc" - không thể thay đổi:

Thuộc tính readOnly của Input Month trong HTML DOM

Thuộc tính readOnly của Input Month trong HTML DOM

Nhấn "Đọc & Ghi" - có thể thay đổi lại:

Thuộc tính readOnly của Input Month trong HTML DOM

🔑 So sánh readOnly vs disabled:
Đặc điểmreadOnlydisabled
Người dùng thấy giá trị✅ Có✅ Có (mờ)
Người dùng sửa được❌ Không❌ Không
Gửi giá trị khi submit✅ Có❌ Không
Nhận focus✅ Có❌ Không
CSS selector:read-only:disabled