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
150 views
in Technique[技术] by (71.8m points)

javascript - How to prevent number input on keydown?

I want to prevent number input on keydown event on textfield and run custom handler function. Here are the issues

  • e.target.value is useless since the key value is not projected into the target value yet
  • e.keyCode for number depends on keyboard type, language layout, Fn or Shift key
  • String.fromCharCode(e.keyCode) is not reliable, at least on my keyboard (Czech qwerty)
  • w3 specification says e.keyCode is a legacy attribute and suggests e.char instead, but it is not implemented in browsers yet

So how to catch the number input before it appears in the textfield?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use the keypress event instead. It's the only key event which will give you information about the character that was typed, via the which property in most browsers and (confusingly) the keyCode property in IE. Using that, you can conditionally suppress the keypress event based on the character typed. However, this will not help you prevent the user from pasting or dragging in text containing numeric characters, so you will still need some kind of extra validation.

My favourite reference for JavaScript key events: http://unixpapa.com/js/key.html

textBox.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
    var charStr = String.fromCharCode(charCode);
    if (/d/.test(charStr)) {
        return false;
    }
};

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

...