I have a function that removes numbers from string, it also should allow for max 5 letters to be entered. When I enter 5, and then another letter or number I can see it in console log, how can I avoid this?
document.getElementById("test").addEventListener("input", (e) => {
console.log(e.target.value);
let temp = e.target.value.replace(/[0-9]/g, '');
e.target.value = temp.substr(0, 5);
})
<input id="test" type="text">
You are loggging the value before removing the excess chars. Just move your console.log to the end of the function.
document.getElementById("test").addEventListener("input", (e) => {
let temp = e.target.value.replace(/[0-9]/g, '');
e.target.value = temp.substr(0, 5);
console.log(e.target.value);
})
<input id="test" type="text">
The problem with your code is that you are reading it from the current target that allows any number of characters, and later you are setting the substring from 0 to 5 on its value.
The simple fix would be to ask HTML to limit the number of characters so that the 6th character is never allowed.
This can be achieved by maxlength property.
<input id="test" type="text" maxlength="5">