按键时忽略输入字符 [英] Ignoring input characters on key down

查看:83
本文介绍了按键时忽略输入字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想忽略手机输入中的某些字符,以便数据库只有数字。我知道我可以在服务器端轻松实现这一点(使用PHP),但我想更好地理解js事件..我的问题是:

I want to ignore certain characters in my phone input, so that the database just has digits. I know I can do this easy on server side (using PHP) but I am trying to understand js events a little better.. My question is this:

如果我有基本输入:

var phoneInput = document.getElementById("phoneInput");

我可以使用onkeydown添加一个事件监听器,工作正常

I can add an event listener using "onkeydown" which works fine

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

但如果我尝试使用'addEventListener'做同样的事情,那么返回false似乎什么都不做

But if I try doing the same thing using 'addEventListener', returning false seems to do nothing

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

我只是不明白为什么。提前感谢任何可以照亮主题的灯光。

I just don't understand why. Thanks in advance for any light you can shine on the subject..

推荐答案

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

I would strongly advise against changing the user's input or otherwise prevent them from typing something while they're doing it. It is confusing and leads to a bad user experience.

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

Ideally, you should keep your server-side validation and then use HTML5 features such as these:

<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 属性进行自定义。)

Modern browsers will prevent the form from being submitted and present helpful error message to the user (which you can customise with a title attribute).

但是,作为一般参考, return false; 不一定取消该事件。要做到这一点,你应该使用它:

However, for general reference, return false; doesn't necessarily cancel the event. To do that, you should use this:

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

这篇关于按键时忽略输入字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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