jquery keyup function check if number

后端 未结 8 1890
南旧
南旧 2020-12-10 02:59

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\').k         


        
8条回答
  •  北海茫月
    2020-12-10 03:32

    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/

提交回复
热议问题