Reputation: 17683
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"/>
Upvotes: 0
Views: 503
Reputation: 20102
you should use the keydown
event instead of the keyup
. I'd do it like this:
var inputs = $$('.numberOnly');
inputs.addEvent('keydown', function(e){
if (e.code >= 48 && e.code <= 57 ){
return true;
}
e.stop();
return false;
});
Hope this helps
EDIT:
Maybe you'd want to allow the "tab" key ,the "enter" key and the "backspace" too =P
Upvotes: 1