1
How to intercept and cancel pressed key in IE and firefox?
I’m trying to javascript
pure but if there is no way can be JQuery
.
I used the code below but it only worked on 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:
In html: onkeypress="return numbersOnly(this, event);"
In the JS:
function numbersOnly(oToCheckField, oKeyEvent) {
return oKeyEvent.charCode === 0 || /\d/.test(String.fromCharCode(oKeyEvent.charCode));
}
But I actually wanted to use it on a eventlistener
of all inputs, does not work in this code below:
``` Test keypress interception
<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>
```
It’s not related to the question, but I’ll leave it here a question on creating attributes that do not exist, e.g:
permitidos
. If you want to create custom attributes, use data-Attributes.– Renan Gomes
@Renan, thanks, I’m gonna read.
– João Paulo