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

HTML DOM Input Number readOnly Property: อ่านอย่างเดียว

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

รูปแบบ (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; outline: none; }
        .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 number readOnly property</h1>
    <p>สวัสดี เลือกวันเกิดของคุณ?</p>
    <input type="number" class="numberInput">
    <button onclick="rFunction()" class="btn">Read Only</button>
    <button onclick="rWFunction()" class="btn">Read & Write</button>
    <script>
        function rFunction() {
            var numberInput = document.querySelector(".numberInput");
            numberInput.readOnly = true;
        }
        function rWFunction() {
            var numberInput = document.querySelector(".numberInput");
            numberInput.readOnly = false;
        }
    </script>
</body>
</html>

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

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

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

  • แสดงค่าที่คำนวณแล้ว (ราคารวม, ภาษี, ส่วนลด)
  • แสดง ID หรือรหัสที่ระบบสร้างให้
  • โหมดดูข้อมูล (view mode) ในระบบ CRUD