jquery keyup function check if number

Adam Sam picture Adam Sam · Jun 20, 2013 · Viewed 89.9k times · Source

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?

Answer

Kevin Bowersox picture Kevin Bowersox · Jun 20, 2013

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/