0
Below I have two fields using the same function. In the first field I use the onkeydown
and in the second onkeyup
:
function eventos(e){
if(isNaN(e.key)){
e.preventDefault();
return;
}
console.log("Um número foi digitado");
}
document.getElementById("campo1").onkeydown = eventos;
document.getElementById("campo2").onkeyup = eventos;
Digite apenas números (evento keydown):
<br>
<input id="campo1">
<br><br>
Digite apenas números (evento keyup):
<br>
<input id="campo2">
In the function I check if what was typed is a number with isNaN(e.key)
. If what was typed is not a number, will enter the if
, cancel event and exit function (return
). However, only at the event onkeydown
, if any key other than a number is entered, the event is canceled normally and nothing happens in the input. But in the event onkeyup
, if I type a letter, for example, the letter is inserted in the input.
I’d like to know why preventDefault()
work in one and not work in the other event.
I searched the MDN and there it says that the event keyup
is cancellable.
I think that’s how the JS API works, the value is embedded in the keydown, the keyup is no use validating, because the data entry was in the keydown. In my opinion the data is entered in the "press", not in the "release" then as you will validate if it is number if there has already been the input of the data... I’m not sure what I’m talking about, but it’s what you look like looking at as layman on the subject
– hugocsl
Hmm... makes sense and lit a little light at the end of the tunnel.
– Sam
It’s like you get shot and then put the vest on, you have to put the vest on before the shot comes. You have to validate before the bullet enters, not after it has already entered...: D
– hugocsl
It really makes sense what you said.
– Sam
The event is canceled, so much so that the
console.log
is not shown, but this does not take away the characters that are already there.– Isac
@Isac does not enter the console because of
return
. That is, in the keyup event, whether or not preventDefault() is there.– Sam
The cancellation of the event may serve in the effects of Bubbling of the event, where it is canceled and other elements no longer capture it, but not to delete content from the field. But only by confirming in the same source.
– Isac