防止在输入类型编号中输入非数字 [英] Prevent typing non-numeric in input type number

查看:85
本文介绍了防止在输入类型编号中输入非数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用< input type = number> 会导致事件侦听器内的 this.value 返回如果输入不是有效的数字,则为空字符串。你可以在 http://jsfiddle.net/fSy53/ 看到这方面的例子。

Using <input type=number> will cause this.value inside of an event listener to return an empty string if the input is not a valid number. You can see an example of this at http://jsfiddle.net/fSy53/

然而,无效字符仍显示在输入中。

However, the invalid characters are still displayed in the input.

有什么方法可以获取实际显示的 ,包括来自事件监听器内的无效字符?

Is there any way to get the value that is actually displayed, including the invalid characters, from within an event listener?

我的最终目标是防止用户实际输入字段中的任何非数字字符。我需要使用 type = number ,以便移动设备使用数字虚拟键盘。我的目标是在<$ c $上执行诸如 this.value = this.value.replace(/ [^ 0-9。] / g,) c> keyup keypress ,但这不起作用,因为如果输入无效字符,从 this.value 读取返回

My ultimate goal is to prevent users from actually typing any non-numeric characters into the field. I need to use type=number so that the numeric virtual keyboard is used by mobile devices. My goal would be to do something like this.value = this.value.replace(/[^0-9.]/g, "") on keyup keypress, but this doesn't work because if an invalid character is typed, reading from this.value returns "".

推荐答案

尝试防止默认行为,如果您不喜欢传入的密钥value:

Try preventing the default behaviour if you don't like the incoming key value:

document.querySelector("input").addEventListener("keypress", function (evt) {
    if (evt.which < 48 || evt.which > 57)
    {
        evt.preventDefault();
    }
});

这篇关于防止在输入类型编号中输入非数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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