The block of code that's causing me trouble is this:
btn.addEventListener('click', ()=> {
if (!gamePlay) {
gamePlay=true
btn.innerHTML="Check Combo"
makeGame(6)
} else {
const inputs=Array.from(document.querySelectorAll('input'))
for (let i=0; i<inputs.length; i++) {
if (inputs[i].value!==inputs[i].correct) {
instructions.innerHTML=`Guesses ${++guesses}`
console.log(inputs[i].value)
return
} else {
instructions.innerHTML=`It took you ${guesses} to win`
}
}
}
})
It's clearly selecting the input elements before the user has changed the values of any. How do I restructure the code so that the program captures the input elements after the user has changed number values? I think it's because I placed this block of code too early.
As a result, even if the user gets the combination right, the input values are all empty so you'll never get to the else block.
Can anyone explain whats happening and how to fix this?
It's clearly selecting the input elements before the user has changed the values of any.
This isn’t true, but it wouldn’t matter if it were. The only important thing is that they exist when they’re selected, which they do.
As a result, even if the user gets the combination right, the input values are all empty
You’re logging the values to the console with console.log(inputs[i].value)
. They aren’t empty, right?
The real issue is that the correct
property is a number:
el.correct=Math.floor(Math.random()*5)+1
and the value
property you’re comparing it to:
if (inputs[i].value!==inputs[i].correct) {
is a string. !==
requires its operands to have the same type. Convert the value to a number to compare it:
if (Number(inputs[i].value) !== inputs[i].correct) {