Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

HTML DOM Input Month readOnly Property: สถานะอ่านอย่างเดียว

คุณสมบัติ readOnlyของ input type="month" คืนค่าและกำหนดว่าช่องเลือกเดือนเป็นอ่านอย่างเดียว (ไม่สามารถแก้ไขได้ แต่ส่งค่าไปกับฟอร์มได้)

รูปแบบ (Syntax)

อ่านค่า:

object.readOnly

กำหนดค่า:

object.readOnly = true | false

ตัวอย่างการใช้งาน

สลับสถานะ read-only และ read-write:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; color: #fff; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat; height: 100vh; }
        p { font-weight: 700; font-size: 1.1rem; }
        input { display: block; width: 35%; border: 2px solid #fff; background-color: transparent; color: #fff; font-weight: bold; padding: 8px; margin: 1rem auto; }
        .btn { background: #0197F6; border: none; height: 2rem; border-radius: 2px; width: 35%; margin: 2rem auto; display: block; color: #fff; outline: none; cursor: pointer; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง Input month readOnly property</h1>
    <p>สวัสดี เลือกเดือนเกิดของคุณ?</p>
    <input type="month" class="monthInput">
    <button onclick="rFunction()" class="btn">Read Only</button>
    <button onclick="rWFunction()" class="btn">Read & Write</button>
    <script>
        function rFunction() {
            var monthInput = document.querySelector(".monthInput");
            monthInput.readOnly = true;
        }
        function rWFunction() {
            var monthInput = document.querySelector(".monthInput");
            monthInput.readOnly = false;
        }
    </script>
</body>
</html>

ความแตกต่างระหว่าง readOnly และ disabled

คุณสมบัติreadOnlydisabled
ผู้ใช้แก้ไขได้ไหมไม่ได้ไม่ได้
ส่งค่าไปกับฟอร์มส่งได้ไม่ส่ง
สามารถโฟกัสได้ไหมได้ไม่ได้
CSS pseudo-class:read-only:disabled

การใช้งานจริง

  • แสดงค่าที่คำนวณแล้ว ไม่อนุญาตให้ผู้ใช้แก้ไข
  • แสดงข้อมูลจากฐานข้อมูลในโหมดดูอย่างเดียว (view mode)
  • ป้องกันการแก้ไขฟิลด์สำคัญ แต่ยังส่งค่าไปเซิร์ฟเวอร์