Pergunta

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

Foi útil?

Solução

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;
    }
});

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top