JavaScript密钥代码仅允许数字和加号

问题描述:

我有这个JavaScript函数,用于强制用户只在文本框中键入数字。现在,我想修改此功能,以便用户输入加号(+)符号。如何实现这个目标?

I have this JavaScript function that is used to force user only type number in the textbox. Right now and I want to modify this function so it will allow the user to enter plus (+) symbol. How to achieve this?

//To only enable digit in the user input

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}


由于'+'符号十进制ASCII代码为43,您可以将其添加到您的条件中。

Since the '+' symbol's decimal ASCII code is 43, you can add it to your condition.

例如:

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode != 43 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

这样,Plus符号是允许的。

This way, the Plus symbol is allowed.