Вопрос

$('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