Detect numbers or letters with jquery/javascript?

2020-02-16 06:57发布

I want to use an if-statement to run code only if the user types in a letter or a number.

I could use

 if(event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50..) {
       // run code
 }

Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?

11条回答
地球回转人心会变
2楼-- · 2020-02-16 07:20
if(event.keyCode >= 48 && event.keyCode <= 90) {
    //the key pressed was alphanumeric
}
查看更多
Melony?
3楼-- · 2020-02-16 07:23

use $.isNumeric(value); return type is boolean

查看更多
\"骚年 ilove
4楼-- · 2020-02-16 07:24

As @Gibolt said, you should Use event.key

Because charCode, keyCode and Which are being deprecated.

查看更多
淡お忘
5楼-- · 2020-02-16 07:28

For Numeric Values:

function ValidNumeric()
    {
        var charCode = (event.which) ? event.which:event.KeyCode;
        if (charCode>=48 && charCode<=57) 
        {
        return true;
        }
        else
        return false;
    }

Here, 48 and 57 is the range of numeric values.

For Alphabetic:

function ValidAplpha()
{
    var charCode = (event.which) ? event.which:event.KeyCode;

    if(charCode >= 65 && charCode <= 90 || charCode>=97 && charCode<=122)
    {
    return true;
    }
    else
    return false;
}

Here, 65 to 90 is the range for Capital alphabates (A-Z) and 97 to 122 is range for small alphabates (a-z)

查看更多
ゆ 、 Hurt°
6楼-- · 2020-02-16 07:31

You can also use charCode with onKeyPress event:

if (event.charCode > 57 || event.charCode < 48) {
    itsNotANumber();
}
else {
    itsANumber();
}
查看更多
登录 后发表回答