$('input').keypress(function(e) {
        var regex = new RegExp("^[a-zA-Z0-9]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
           event.preventDefault ? event.preventDefault() : event.returnValue = false;
        }
    });

how to fix this to work in IE. The idea is to escape special characters on keypress. works good in chrome, mozilla etc but IE ignores all keypress function even its valid for regexp.

有帮助吗?

解决方案

Use the following code

$('input').keypress(function(e) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (!regex.test(key)) {
       e.preventDefault ? e.preventDefault() : e.returnValue = false;
    }
});

其他提示

$('input').keypress(function(e) <--- use e.preventDefault();

$('input').keypress(function(event) <--- use event.preventDefault();

Whatever param you pass to function, use that to call event object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top