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.
4
Answers
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 menu
ordrag&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 …
This isn’t necessarily the answer you are looking for, but you can do the same with the help of RegEx. Use
match
to find out if the input has the restricted characters and if yes, remove it with help ofreplace
.As Kobra mentioned, you will need to capture the key during the
keydown
event.I modified their response below; particularity decoupling the key check from the event handler.
Quoting the OP …
The input already happened, it’s too late to prevent the changes which came along with it.
In order to achieves the OP’s actual goal, a solution which omits such data for any kind of user input, needs to implement an immediate auto correction which also adapts the input element’s caret position according to the user’s most recent input action …