I have 10 buttons in html that represents numbers from 0 to 9 that i'm using like keyboard for the number guessing game. After i find a way to get id of every button on the click with the for loop and Event listener, every other function stopped to work and i got the TypeError of -Cannot read property 'addEventListener' of undefined-. Here is the html:
let buttons = document.getElementsByClassName("number-box");
let buttonsCount = buttons.length;
for (let i = 0; i <= buttonsCount; i++) {
buttons[i].addEventListener('click', returnId)
};
function returnId(buttons) {
let whatHappens;
switch (this.id) {
case "zero":
whatHappens = console.log('zero');
userInput.value += 0;
break;
case "one":
whatHappens = console.log('one');
userInput.value += 1;
break;
case "two":
whatHappens = console.log('two');
userInput.value += 2;
break;
case "three":
whatHappens = console.log('two');
userInput.value += 3;
break;
case "four":
whatHappens = console.log('two');
userInput.value += 4;
break;
case "five":
whatHappens = console.log('two');
userInput.value += 5;
break;
case "six":
whatHappens = console.log('two');
userInput.value += 6;
break;
case "seven":
whatHappens = console.log('two');
userInput.value += 7;
break;
case "eight":
whatHappens = console.log('two');
userInput.value += 8;
break;
case "nine":
whatHappens = console.log('two');
userInput.value += 9;
break;
default:
whatHappens = console.log('nothing');
}
return whatHappens;
}
<div class="container animate__animated animate__headShake">
<button class="number-box" id="zero">0</button>
<button class="number-box" id="one">1</button>
<button class="number-box" id="two">2</button>
<button class="number-box" id="three">3</button>
<button class="number-box" id="four">4</button>
<button class="number-box" id="five">5</button>
<button class="number-box" id="six">6</button>
<button class="number-box" id="seven">7</button>
<button class="number-box" id="eight">8</button>
<button class="number-box" id="nine">9</button>
</div>
So, this code actually works, but i'm getting an error and other functions stopped to work. What should i do?