jquery keyup 函数检查数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17209180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:38:34  来源:igfitidea点击:

jquery keyup function check if number

jqueryfunctioncharacterkeyup

提问by Adam Sam

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?

但问题是,当用户按住带有字符的键时,功能 keyup 不会触发......有什么想法我可以禁止吗?

回答by Kevin Bowersox

Try binding to the keypressevent 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.

尝试绑定到keypress事件而不是keyup. 按住某个键时,它会反复触发。当按下的键不是数字时,您可以调用preventDefault()这将防止键被放置在输入标签中。

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

工作示例:http : //jsfiddle.net/rTWrb/2/

回答by Richard P.

I decided to use the answer provided by @Rahul Yadav, but it is erroneous since it doesn't consider num pad keys, which have different codes.

我决定使用@Rahul Yadav 提供的答案,但这是错误的,因为它没有考虑具有不同代码的数字键盘键。

Here, you can see a excerpt of the code table:

在这里,您可以看到代码表摘录

Here the function I implemented:

这里我实现的功能:

function isNumberKey(e) {
    var result = false; 
    try {
        var charCode = (e.which) ? e.which : e.keyCode;
        if ((charCode >= 48 && charCode <= 57) || (charCode >= 96 && charCode <= 105)) {
            result = true;
        }
    }
    catch(err) {
        //console.log(err);
    }
    return result;
}

回答by instead

The best way is to check value of input, instead of pressed key. Because there are tabs, arrows, backspace and other characters that need to be checked when You use character code.

最好的方法是检查输入的值,而不是按键。因为在您使用字符代码时,有制表符、箭头、退格符等需要检查的字符。

That code check input value after user pressed a key:

用户按下某个键后,该代码检查输入值:

$('#p_first').keyup(function(){
    while(! /^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/.test($('#p_first').val())){
        $('#p_first').val($('#p_first').val().slice(0, -1));
    }
});

While loop remove last character until input value is valid. Regex /^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/validate integer and float number eg. "12,12", "12.1", "12.". It is important that number "12." (dot at the end) also be valid!Otherwise user can't enter any period.

While 循环删除最后一个字符,直到输入值有效。正则表达式/^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/验证整数和浮点数,例如。“12,12”、“12.1”、“12.”。数字“12”很重要。(点在最后)也有效!否则用户不能输入任何时间段。

And then on submit regex check for valid float number ([0-9]{1,2})instead of ([0-9]{0,2}):

然后提交正则表达式检查有效浮点数([0-9]{1,2})而不是([0-9]{0,2})

$('form').submit(function(e){
    if(! /^([0-9]+)((\.|,)([0-9]{1,2}))?$/.test($('#p_first').val())){
        $('#p_first').addClass('error');
        e.preventDefault();
    }
});

Notice:It is better to assign $('#p_first')into variable. var input = $('#p_first');

注意:最好赋值给$('#p_first')变量。var input = $('#p_first');

回答by Krunal Hingu

Try This..it may usefull.

试试这个..它可能有用。

<HTML>
<input type="text" name="qty" id="price" value="" style="width:100px;" field="Quantity" class="required">
</HTML>

<script>
 $(document).ready(function() {
$('#price').live('keyup',function(){
        this.value = this.value.replace(/[^0-9\.]/g,'');
        });
});
</script>

回答by Sacky San

I used the following function to check if a given string is number or not. This implementation works on keyup and keydown and also takes care of numpad keys

我使用以下函数来检查给定的字符串是否为数字。此实现适用于 keyup 和 keydown 并且还处理小键盘键

// Validate Numeric inputs
function isNumber(o) {
    return o == '' || !isNaN(o - 0);
}

Assuming that your key code on the keyup or keydown event is in keyCode variable:

假设您在 keyup 或 keydown 事件上的键代码在 keyCode 变量中:

var keyCode = e.keyCode || e.which;
if (keyCode >= 96 && keyCode <= 105) {
        // Numpad keys
        keyCode -= 48;
}
console.log(isNumber(String.fromCharCode(keyCode)));
console.log(isNumber($(this).val() + String.fromCharCode(keyCode)));

Return false if the return value from isNumber is false:

如果 isNumber 的返回值为 false,则返回 false:

    var txtVal = $(this).val() + String.fromCharCode(keyCode);
    if (!isNumber(txtVal)) {
        e.returnValue = false;
    }

回答by Gibolt

With a key event, use event.keyto get the actual value. To check if integer:

使用键事件,用于event.key获取实际值。要检查是否整数:

isFinite(event.key);

An easier HTML solution would be to use the numbertype input. It restricts to only numbers (kind of).

更简单的 HTML 解决方案是使用number类型输入。它仅限于数字(种类)。

<input type="number">

Either way, you should clean all user input with:

无论哪种方式,您都应该使用以下命令清理所有用户输入:

string.replace(/[^0-9]/g,'');

回答by Rahul Yadav

JavaScript:

  function isNumberKey(a){
  var x=a.val();
  a.val(x.replace(/[^0-9\.]/g,''));

}

HTML:

     <td><input type="text" name="qty" onkeypress="onkeyup="return isNumberKey($(this));"" value="" style="width:100px;" field="Quantity" class="required"></td>