jquery keyup function check if number
I decided to use the answer provided by @Rahul Yadav, but it is erroneous since it doesn't consider num pad keys, which have different codes.
Here, you can see a excerpt of the code table:
Here the function I implemented:
function isNumberKey(e) {
var result = false;
try {
var charCode = (e.which) ? e.which : e.keyCode;
if ((charCode >= 48 && charCode <= 57) || (charCode >= 96 && charCode <= 105)) {
result = true;
}
}
catch(err) {
//console.log(err);
}
return result;
}
Try binding to the keypress
event instead of keyup
. It gets fired repeatedly when a key is held down. When the key pressed is not a number you can call preventDefault()
which will keep the key from being placed in the input tag.
$('#p_first').keypress(function(event){
if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
event.preventDefault(); //stop character from entering input
}
});
Working Example: http://jsfiddle.net/rTWrb/2/