Jquery keypress 37 issue, '%' and [ left arrow ] not work in IE 10

一曲冷凌霜 提交于 2019-12-11 21:09:04

问题


Good morning,

I facing a issue on the IE 10 where my keypress still can enter '%' but the FF and Chrome no such issue. I found out that the key 37 is the [ left arrow ] which match with '%' in ASCII. My sample code as below:

$('#refId').bind("keypress", function(event) {
            // allow  letters, numbers and keypad numbers ONLY
            var key = event.charCode;
            if((key >= 48 && key <= 57) ||
                (key >= 65 && key <= 90) ||
                (key >= 97 && key <= 122)){
                return true;
            }

            //allow backspace, tab, left arrows, right arrow, delete
            key = event.keyCode;
            if(key == 8 || 
                    key == 9 ||
                    key == 37 ||
                    key == 39 ||
                    key == 46){
                return true;
            }

            return false; 
    });

Can give me some idea how to fix this?

Thanks. -fsloke


回答1:


Use var key = event.which; instead and join the if-statements.

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

- https://api.jquery.com/event.which/

$('#refId').on("keydown", function(event) {
    // allow letters, numbers and keypad numbers ONLY
    var key = event.which;
    if((key >= 48 && key <= 57) ||
        (key >= 65 && key <= 90) ||
        (key >= 97 && key <= 122) ||
        key == 8 || 
        key == 9 ||
        key == 37 ||
        key == 39 ||
        key == 46) {
        return true;
    }

    return false; 
});


来源:https://stackoverflow.com/questions/31331548/jquery-keypress-37-issue-and-left-arrow-not-work-in-ie-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!