Preventing direct processing of html5 number input field
I created html5 number input field like this:
<input type="number" min="1" max="51" value="1"/>
Now I want the user to be able to cycle through the numbers using the up and down arrow buttons. However, I don't want the user to be able to directly enter a new number in the field. How to do it?
I tried to install readonly="true"
, but as expected it also disabled the user's ability to cycle through numbers using the up and down arrow buttons.
source to share
You can call preventDefault when a key is pressed, if only the arrow keys are:
var numInput = document.getElementsByTagName('input')[0];
numInput.addEventListener('keypress', function (event) {
if (event.keyCode !== 38 && event.keyCode !== 40) {
event.preventDefault();
}
});
Here's a jsfiddle for a demo. If you don't need the arrow keys on your keyboard, you can omit this part of the check and just disallow the default on any key press.
source to share
event.preventDefault is an expensive operation compared to returning, so jsbin_example
<input type="number" min="1" max="51" value="1"/>
$("input").on("keydown",function update(event)
{
var keyCod,
srcObj = event.src||event.originalTarget||event.target;
if(event.keycode || event.which)
{
keyCod = event.keycode || event.which;
}
else
{
keyCod = event;
}
if(!(keyCod == 38 || keyCod == 40))
{
return false;
}
console.log('after false');
if(keyCod == 38)
{
srcObj.value = parseInt(srcObj.value)+1;
}
if(keyCod == 40)
{
srcObj.value = parseInt(srcObj.value)-1;
}
});
source to share