jquery keyup函数检查数字 [英] jquery keyup function check if number
本文介绍了jquery keyup函数检查数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试创建一个输入字段,用户只能在其中输入数字。这个函数已经为我工作了。
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?
推荐答案
尝试绑定到 keypress
事件,而不是 keyup
。当按下键时,它会反复触发。当按下的键不是数字时,您可以调用 preventDefault()
,这将使键不被放在输入标签中。
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
}
});
工作示例: