ใช้ stepUp() และ stepDown() ควบคุม input type=number
เมธอด built-in ของ HTMLInputElement เพิ่ม/ลดค่าตาม step attribute
ตัวอย่างโค้ดเต็ม
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Increment Decrement</title>
</head>
<body>
<input id="demoInput" type="number" min="100" max="110" value="100">
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
<script>
function increment() {
document.getElementById('demoInput').stepUp();
}
function decrement() {
document.getElementById('demoInput').stepDown();
}
</script>
</body>
</html>
วิธีรัน
บันทึกเป็น index.html แล้วเปิดด้วย Live Server
คำอธิบาย
stepUp()เพิ่มค่าตามstepattribute (default = 1)stepDown()ลดค่าตามstepattribute- เคารพ
minและmaxattribute อัตโนมัติ - ไม่ต้อง parseInt/parseFloat เอง
ขยายความสามารถ: กำหนด step และจำนวนครั้ง
<input id="demoInput" type="number" min="0" max="100" step="5" value="0">
<button onclick="stepUp(3)">+15</button> // stepUp(n) เพิ่ม n steps
function stepUp(steps = 1) {
document.getElementById('demoInput').stepUp(steps);
}