【问题标题】:Ignoring input characters on key down忽略按键按下时的输入字符
【发布时间】:2014-07-25 04:57:05
【问题描述】:

我想忽略手机输入中的某些字符,以便数据库只有数字。我知道我可以在服务器端轻松做到这一点(使用 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 即使我定义了数字的输入类型,它仍然允许单词字符。 (我在Firefox中开发,但我相信大多数浏览器都是一样的)
  • 我知道,但它是一家相对较小的公司(30 名员工)的内部应用程序,所以我告诉他们不要使用 IE。另外,在将 PHP 中不需要的字符插入数据库之前,我会删除它们,但就像我说的那样,我只是想了解 JS 处理这些事情的方式。谢谢!

标签: javascript


【解决方案1】:

我强烈建议不要更改用户的输入或以其他方式阻止他们在输入内容时输入内容。这令人困惑并导致糟糕的用户体验。

理想情况下,您应该保留服务器端验证,然后使用 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;

【讨论】:

  • 谢谢!是的,我同意不断变化的用户输入,我觉得这很烦人,但我只是在尝试一些不同的东西,我认为 onkeydown 和 addEventListener("keydown" 等.. 的行为不同,这很奇怪—— - stackoverflow 让我等待 3 分钟来接受你的回答,但我会
【解决方案2】:

我必须为我正在进行的项目做类似的事情。我就是这样做的。

// 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();
        }
    }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-03
    • 2013-11-21
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 2016-07-02
    • 1970-01-01
    相关资源
    最近更新 更多