This question has been asked and answered before; none of the previous answers given here seem to fix my situation. Therefore I need to ask, once again, why isn't the event prevented correctly?
document.addEventListener("input", event => {
if(event.data == '#' || event.data == '+' || event.data == '.' || event.data == ';'){
event.preventDefault();
alert("Non-allowed character detected: " + event.data);
return false;
}
});
I have tried different versions, for example I added the event.stopPropagation() and event.stopImmediatePropagation() but nothing changed. What am I doing wrong and how do I fix it?
It might help to know that I'm simply trying to stop the input of certain characters.
Your code does not prevent input because you are using an
"input"event. The event listener"input"is fired after the input occurs, so its default cannot be prevented.Instead, use
"keydown"which fires before the action, hence the default action can be prevented.Here is your updated code:
Also, if you want to stop someone from pasting in such characters using the
context menuordrag&drop, you can use all these functions together:Or if you really want to use
input, you can, but first the content will be written, then deleted from the input:All relevant parts of the above code as executable stack snippet ...