I'm trying to prevent non-numeric characters being entered in a text field. My code validates the characters but doesn't stop it being added to text box.
My code:
var isNumberKey = function(e){
//alert(e.which);
if (e.which > 31 && (e.which < 48 || e.which > 57))
return false;
return true;
}
var isBackSpaceKey = function(e){
return e.which == 8;
}
var isArrowKey = function(e) {
return e.which >= 37 && e.which <= 40;
}
var inputs = $$('.numberOnly');
inputs.addEvent('keyup', function(e){
console.log(e.which);
if (!isNumberKey(e) && !isBackSpaceKey(e) && !isArrowKey(e)){
e.stop();
return false;
}
return true;
});
HTML:
<input name="t1" type="text" class="numberOnly" id="t1"/>
you should use the
keydown
event instead of thekeyup
. I'd do it like this:http://jsfiddle.net/TsAkb/
Hope this helps
EDIT:
Maybe you'd want to allow the "tab" key ,the "enter" key and the "backspace" too =P