JavaScript密钥代码仅允许数字和加号 [英] JavaScript keycode allow number and plus symbol only

查看:101
本文介绍了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.

这篇关于JavaScript密钥代码仅允许数字和加号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆