質問

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