i am trying to create an input field where the user can only type in numbers. this function is already working almost fine for me:
$('#p_first').keyup(function(event){
if(isNaN(String.fromCharCode(event.which))){
var value = $(this).val();
$(this).val(value.substr(0,value.length-1));
}
});
but the problem is, whe the user holds the key with an character the function keyup is not triggering.... any ideas how i can forbid this?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With