Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

javascript - Ignoring input characters on key down

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:

If I have a basic input:

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

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;
};

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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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).

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...