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

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

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

Cú pháp

Lấy giá trị:

numberInput.readOnly

Thiết lập giá trị:

numberInput.readOnly = true | false

Ví dụ: Toggle 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="number"] {
            display: block; width: 35%; margin: 15px auto;
            border: 2px solid white; background: transparent;
            color: white; font-weight: bold; padding: 8px; outline: none;
        }
        .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 Number readOnly Property</h1>
    <p>Ngày sinh của bạn (1-31)?</p>
    <input type="number" class="numberInput" min="1" max="31">
    <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(".numberInput").readOnly = true;
        }
        function setReadWrite() {
            document.querySelector(".numberInput").readOnly = false;
        }
    </script>
</body>
</html>

Kết quả

Nhập số rồi nhấn "Chỉ đọc" - không thể sửa:

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

Nhấn "Đọc & Ghi" - có thể sửa lại:

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

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

✅ Khi nào dùng readOnly:
  • Hiển thị giá trị tính toán (tổng tiền, thuế) mà không cho sửa.
  • ID record khi edit (người dùng xem nhưng không đổi ID).
  • Cần gửi giá trị lên server (disabled thì không gửi).