Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top