Adam Sam Adam Sam - 8 months ago 77
jQuery Question

jquery keyup function check if number

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:

var value = $(this).val();


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.


       if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
           event.preventDefault(); //stop character from entering input


Working Example: