What is keyCode 229?

转自https://gielberkers.com/what-is-keycode-229/

So today I stumbled into another fine situation: I had an input-field in a form that would only require numbers. To prevent the user from entering numbers I created a simple JavaScript method that looked something like this:

/**
 * This method is fired on each keydown-event of the input field
 * @param e 
 */
function checkIfKeyIsNumber(e)
{
    if(
        !(e.keyCode >= 48 && e.keyCode <= 57) &&  // 0-9
        !(e.keyCode >= 96 && e.keyCode <= 105) // numpad 0-9
        // some more checking like arrows, delete, backspace, etc.
    ) {
        // This is not a valid key
        e.preventDefault();
    }
}

This works fine.

Except for some Android phones.

Not all.

Some.

So what was going on?

keyCode 229

After some trial and error and debugging I finally discovered that in some situations on Android (and most likely other browsers as well) a different keyCode was sent: 229. But what is keyCode 229?

Well according to an interesting answer on Stack Overflow by James Newton some browsers send this keyCode to the input field as some kind of placeholder for a combined character. Take the character é for example: on most systems you can type this character by first typing a ´ (the input field will now show an underlined ´ in most cases) followed by pressing an e .

I believe that the same happens on browsers for mobile devices. I haven’t checked it thoroughly, since I first encountered this problem today, but I believe that a mobile device will send the ‘placeholder keycode’ the the input-field to say: “hey, my human is still typing something, but you better prepare for some text coming your way”.

Unfortunately, having an e.preventDefault() fired on that moment isn’t helping.

A quick fix

The quick fix I implemented now is to simply whitelist keyCode 229 to my list of allowed keyCodes:

/**
 * This method is fired on each keydown-event of the input field
 * @param e 
 */
function checkIfKeyIsNumber(e)
{
    if(
        !(e.keyCode >= 48 && e.keyCode <= 57) &&  // 0-9
        !(e.keyCode >= 96 && e.keyCode <= 105) // numpad 0-9
        // some more checking like arrows, delete, backspace, etc.
        && e.keyCode != 229 // Check for the 'placeholder keyCode'
    ) {
        // This is not a valid key
        e.preventDefault();
    }
}

I’m not sure if this is the most elegant or correct fix for this problem, but it worked for me. And as soon as it stops working (or some of you guys have a better solution that you can put in the comments) I’d be happy to update this article.

我尝试了上面作者的方法,但是结果依然是错误。后来就放弃了使用这种方法,转而使用在input方法中使用正则表达式判断新输入的字符,如果无效就替换为空。
关于KeyCode更详细的信息,可以看W3C的文档http://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html。

查看keyCode的页面http://keycode.info/

如果有同行知道更好的方法,希望可以交流一下。

你可能感兴趣的:(What is keyCode 229?)