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