I'm creating a wordle like input scheme, where each input has only 1 character, and typing in one automatically sends you to the next. The problem is, of course, you can't hit backspace to go to the previous one, so I implemented it with the following code:
let inputs = document.getElementsByTagName("input");
document.body.addEventListener("keyup", function (e) {
if (e.keyCode === 8) {
for (let i = 0; i < inputs.length; i++) {
if (inputs[i].value == "" && i > 0 && inputs[i] == document.activeElement) {
inputs[i - 1].value = "";
inputs[i].value = ""
inputs[i - 1].focus();
break
}
}
}
});
I expect the code to simply register the backspace key just once, but instead it reports it a number of times, causing the whole row to be erased when I hit the key just once. Sometimes it can be just 10, other times hundreds. Why is this? How can I fix this? I'd additionally like to mention that I do not want to use jQuery and want to keep this pure JavaScript.