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

HTML DOM Input Number Object: คุณสมบัติและเมธอดครบถ้วน

HTML DOM Input Number Object แทนอิลิเมนต์ <input type="number"> ใช้สร้างและจัดการช่องกรอกตัวเลขพร้อม spinner

รูปแบบการสร้าง (Syntax)

var numberInput = document.createElement("INPUT");
numberInput.setAttribute("type", "number");

คุณสมบัติหลัก (Properties)

คุณสมบัติคำอธิบาย
autocompleteคืนค่าและกำหนด autocomplete attribute
autofocusคืนค่าและกำหนดโฟกัสอัตโนมัติ
disabledคืนค่าและกำหนดสถานะปิดใช้งาน
defaultValueคืนค่าและกำหนดค่าเริ่มต้น
formคืนค่ารีเฟอร์เรนซ์ของฟอร์มที่ครอบคลุม
listคืนค่ารีเฟอร์เรนซ์ของ datalist ที่เกี่ยวข้อง
maxคืนค่าและกำหนดค่าสูงสุด
minคืนค่าและกำหนดค่าต่ำสุด
nameคืนค่าและกำหนดแอตทริบิวต์ name
readOnlyคืนค่าและกำหนดสถานะอ่านอย่างเดียว
requiredคืนค่าและกำหนดว่าบังคับกรอกหรือไม่
stepคืนค่าและกำหนดช่วงขั้น (ค่าเริ่มต้น 1)
typeคืนค่า "number" (อ่านอย่างเดียว)
valueคืนค่าและกำหนดค่าปัจจุบัน
placeholderคืนค่าและกำหนด placeholder text

เมธอด (Methods)

เมธอดคำอธิบาย
stepUp(n)เพิ่มค่าขึ้น n (ค่าเริ่มต้น 1)
stepDown(n)ลดค่าลง n (ค่าเริ่มต้น 1)

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

สร้าง number input ใหม่ (โค้ดตัวอย่างเดิมมี bug ใช้ month input แทน number แก้ไขแล้ว):

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; background-color: #363946; color: #fff; }
        .btn { background-color: #db133a; border: none; height: 2rem; border-radius: 50px; width: 60%; margin: 2rem auto; display: block; color: #fff; outline: none; cursor: pointer; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง Input Number Object</h1>
    <button onclick="createNumberField()" class="btn">สร้างช่องกรอกตัวเลข</button>
    <script>
        function createNumberField() {
            var numberInput = document.createElement("INPUT");
            numberInput.setAttribute("type", "number");
            numberInput.setAttribute("value", "42");
            numberInput.setAttribute("min", "0");
            numberInput.setAttribute("max", "100");
            numberInput.setAttribute("step", "1");
            document.body.appendChild(numberInput);
        }
    </script>
</body>
</html>

การตรวจสอบความถูกต้อง (Validation)

เบราว์เซอร์จะตรวจสอบอัตโนมัติว่าเป็นตัวเลข อยู่ในช่วง min/max และเป็นพหุคูณของ step

var input = document.querySelector("input[type='number']");
console.log(input.validity); // ValidityState object
console.log(input.validationMessage); // ข้อความ error