How to intercept and cancel key pressed in IE and firefox

1

How to intercept and cancel key pressed in IE and firefox? I'm trying to javascript pure but if I can not be JQuery . I used the code below but it only worked in chrome:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Teste interceptar tecla</title> </head> <body> <input id="teste" type="text" permitidos="123" onkeypress="tratarPreenchimento(this,event)"/> <input type="text" /> <script> function tratarPreenchimento(campo,e) { if (isCaracterPermitido(campo,e) === false) { e.returnValue = false; } } function isCaracterPermitido(campo, e) { var permitidos = campo.getAttribute('permitidos'); if(permitidos) { if (permitidos.indexOf(String.fromCharCode(e.keyCode).toString()) >= 0) { return true; } else { return false; } } else return true; } </script> </body> I found a way: No html: onkeypress="return numbersOnly(this, event);"
In JS: function numbersOnly(oToCheckField, oKeyEvent) { return oKeyEvent.charCode === 0 || /\d/.test(String.fromCharCode(oKeyEvent.charCode)); }

But I actually wanted to use this on% of all inputs, it does not work in this code below:

'' '     Keypress interception test          

<script>
    (function(){
        var inputs = document.querySelectorAll('[type*="text');
        for (var i = 0;i< inputs.length;++i) {
            inputs[i].addEventListener("keypress",tratarKeypress);
        }
        function tratarKeypress(e){
            console.log('Interceptado');
            return e.charCode === 0 || /\d/.test(String.fromCharCode(e.charCode));
        }
    })();

</script>

'' '

    
asked by anonymous 01.03.2016 / 20:28

2 answers

1
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Teste interceptar tecla</title>
    </head>
    <body>
        <input id="teste" type="text" permitidos="123" onkeyup="tratarPreenchimento(this,event)"/>
        <script>
            function tratarPreenchimento(a,evento) {
                if(evento.keyCode != 49 && evento.keyCode != 50 && evento.keyCode != 51){
                    a.value = null;
                }
            }
        </script>
    </body>
</html>

            function tratarPreenchimento(a,evento) {
                if(evento.keyCode != 49 && evento.keyCode != 50 && evento.keyCode != 51){
                    a.value = null;
                }
            }
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Teste interceptar tecla</title>
    </head>
    <body>
        <input id="teste" type="text" permitidos="123" onkeyup="tratarPreenchimento(this,event)"/>
    </body>
</html>

** Try this the problem is that if you type a wrong character after certain it erases everything **

    
01.03.2016 / 21:19
1

I was able to resolve this:

(function () {
    document.onkeypress = function (e) {
        //Código para retornar true ou false;
    };
})();

I tested Chrome, Opera, IE and Firefox.

    
02.03.2016 / 13:17