Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

        $('#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?

like image 501
Adam Sam Avatar asked Jun 20 '13 08:06

Adam Sam


1 Answers

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/

like image 108
Kevin Bowersox Avatar answered Oct 13 '22 17:10

Kevin Bowersox