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