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/

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容