按键按下时忽略输入字符

9
我希望在我的手机输入中忽略某些字符,以便数据库只有数字。我知道可以在服务器端轻松完成此操作(使用PHP),但我正在尝试更好地理解js事件。我的问题是:
如果我有一个基本输入框:
var phoneInput = document.getElementById("phoneInput");

我可以使用“onkeydown”添加事件监听器,这可以很好地工作

phoneInput.onkeydown = function(e){
  var c = String.fromCharCode(e.keyCode);
  var patt = /\d/;
  if(!patt.test(c)) return false;
};

但是,如果我尝试使用“addEventListener”做同样的事情,返回false似乎没有任何效果。

phoneInput.addEventListener("keydown",function(e){
  var c = String.fromCharCode(e.keyCode);
  var patt = /\d/;
  if(!patt.test(c)) return false;
});

我就是不明白为什么。非常感谢您能在这个问题上给予任何帮助。


你在测试哪个浏览器?为什么不使用 type="number"?[你仍然需要支持缺乏支持的浏览器。] - epascarello
@epascarello即使我将输入类型定义为数字,它仍然允许单词字符。(我在Firefox中开发,但我相信大多数浏览器都是一样的) - dano
我知道,但这是一个相对较小的公司(30名员工)内部应用程序,所以我告诉他们不要使用IE。此外,在将它们插入数据库之前,我会在PHP中删除不需要的字符,但正如我所说,我只是想了解JS处理这些事情的方式。谢谢! - dano
2个回答

15

我强烈建议不要更改用户的输入或在他们正在输入时阻止他们输入。这样会导致混淆和糟糕的用户体验。

理想情况下,您应该保留服务器端验证,然后使用HTML5的功能,例如:

<input type="number" /> Allows only numbers
<input type="text" pattern="[0-9. -]*" /> Allows numbers, spaces, periods and hyphens
<input type="text" required /> Specifies a required field

现代浏览器会防止表单提交并向用户展示有用的错误信息(您可以使用title属性自定义)。

然而,为了通用参照,return false; 并不一定会取消事件。要实现这一点,应该使用以下代码:

// if you haven't already:
e = e || window.event;
// to cancel the event:
if( e.preventDefault) e.preventDefault();
return false;

1
谢谢!我同意更改用户输入,我发现这非常烦人,但我只是尝试一些不同的东西,我觉得奇怪的是onkeydown和addEventListener(“keydown”等)没有表现出相同的行为--- stackoverflow让我等待3分钟才能接受你的答案,但我会的。 - dano

5
我曾为正在进行的项目做过类似的事情。这是我的做法。
// prevent users from typing alpha/ symbol characters on select fields
$("#modal-region").on("keydown", "#markdown, #sku", function(e) {

    var key = e.which;
    // when a keydown event occurs on the 0-9 keys the value 
    // of the "which" property is between 48 - 57 
    // therefore anything with a value greater than 57 is NOT a numeric key

    if ( key > 57) {
        e.preventDefault();

    } else if (key < 48) {

    // we don't want to disable left arrow (37), right arrow (39), delete (8) or tab (9)
    // otherwise the use cannot correct their entry or tab into the next field!

        if (key != 8 && key != 9 && key != 37 && key != 39 ) {
            e.preventDefault();
        }
    }

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接