ควบคุม input type number

input number spinner

input type="number" คือกล่องกรอกข้อมูลที่เป็นตัวเลข โดยสำหรับเครื่อง pc เบราเซอร์จะแสดงปุ่มเลื่อนขึ้นลงสำหรับปรับค่าตัวเลขมาให้ เราเรียกปุ่มนี้ว่า spinner.
เมื่อมีปุ่ม spinner เข้ามา การทำงานของ event onkeyup จะใช้งานไม่ได้ถ้าผู้ใช้กดเปลี่ยนค่าที่ spinner นี้ จึงทำให้ต้องเพิ่ม onchange เข้าไปรองรับอีก แต่คราวนี้พอเพิ่มแล้วกลายเป็นว่าทั้ง onkeyup และ onchange จะทำงานซ้อนกันเมื่อผู้ใช้พิมพ์ตัวเลขลงไป.

นี่คือหนึ่งในปัญหาตัวอย่างที่ทำให้โปรแกรมเมอร์บางคนเลิกใช้ input number แล้วหันไปใช้ input text อย่างเก่าไปเลย. แต่บทความนี้ผมจะรวบรวมวิธีปรับแต่งต่างๆของ input number มาให้ได้ครบที่สุดนะครับ.

ปิดการแสดงผลปุ่ม spinner.

วิธีปิดการแสดงผล ให้กำหนด css class สำหรับซ่อน spinner ใน input number ที่ต้องการ. เช่น css class input-no-spinner แล้วกำหนด css ดังต่อไปนี้


.input-no-spinner {
    -moz-appearance: textfield;/* สำหรับเบราว์เซอร์ Firefox รุ่นเก่า */
    appearance: textfield;
}
/* ด้านล่างนี้สำหรับ Chrome, Edge, Safari */
.input-no-spinner::-webkit-outer-spin-button,
.input-no-spinner::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

เมื่อจะนำไปใช้ซ่อน spinner บน input number ที่ต้องการก็เพียงแต่ใส่ class input-no-spinner ลงไป เช่น

<input type="number" class="input-no-spinner">

ปิดใช้งาน mousewheel

ผู้ที่ใช้งานผ่านเครื่อง PC และเมาส์จะสามารถใช้ล้อกลิ้งบนเมาส์ (mousewheel) หมุนเปลี่ยนค่าตัวเลขได้.
วิธีปิดการใช้งาน ให้กำหนดค่า css class สำหรับปิดใช้งานเฉพาะ input number ที่ต้องการดังต่อไปนี้ เช่น input-no-mousewheel-spin โดยนำโค้ด JavaScript/jQuery ต่อไปนี้ไปใช้


$('.input-no-mousewheel-spin').on('wheel', function(e){
    e.preventDefault();
});

เมื่อจะกำหนดให้ input number ใดไม่สามารถใช้ mousewheel ได้ ก็ให้ใส่ css class ดังนี้

<input type="number" class="input-no-mousewheel-spin">

ปิดใช้งาน mousewheel แบบ JavaScript ธรรมดา

let inputNoMousewheel = document.querySelector('.input-no-mousewheel-js');
if (inputNoMousewheel) {
    inputNoMousewheel.addEventListener('wheel', (e) => {
        e.preventDefault();
    });
}

เมื่อจะกำหนดให้ input number ใดไม่สามารถใช้ mousewheel ได้ ก็ให้ใส่ css class ดังนี้

<input type="number" class="input-no-mousewheel-js">

Attributes ต่างๆของ Input number

input number ก็มี attribute มาตรฐานต่างๆเหมือน input text เช่น name, value, disabled, id, autocomplete, autofocus, form, list, readonly, required, placeholder
นอกจากนี้ attribute ที่ใช้ได้กับ input number และ input บางประเภทเท่านั้น เช่น max, min, step

max สำหรับกำหนดค่าตัวเลขสูงสุด.

min สำหรับกำหนดค่าตัวเลขน้อยสุด.

step กำหนดลำดับขั้นตัวเลข เช่น กำหนดเป็น 2 ค่าใน input จะได้ 0, 2, 4, 6, 8, ... โดยมีค่าขึ้นไปทีละ 2 สำหรับตัวเลขที่เป็นบวก.

ใส่ความเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *

คุณอาจใช้แท็กHTMLและแอททริบิวต์เหล่านี้: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>