I have a code that includes an array of words. I also have a place where a user can guess its first letter by typing it into "input-one". If the user guesses the first letter correctly, I’d like to alert "Correct." Therefore, I created a function where I get the first letter of the word and the letter the user typed. However, when I create an "if statement" to check if these letters are equal, nothing alerts. Any help would be appreciated.
const wordList = [
{
word: "Grand",
hint: "Something large"
},
{
word: "Prank",
hint: "A humorous act of deception"
}
]
var a = document.getElementById("inputone"),
a.onkeyup = function() {
if (this.value.length === 1) {
console.log(a.value);
startBtn.onclick = function(){
startBtn.innerHTML = "Submit"
let random = Math.floor(Math.random() * wordList.length);
console.log(random, wordList[random].word);
clueText.innerHTML = wordList[random].hint;
let firstLetter = (random, wordList[random].word.slice(0,1));
let secondLetter = (random, wordList[random].word.slice(-1));
console.log(firstLetter);
console.log(secondLetter);
if (firstLetter == a) {
alert('Correct');
}
}
3
Answers
Tuples don’t exist in Javascript, so I wouldn’t do
(random, wordList[random].word.slice(0,1));
On this line, you have a syntax error:
var a = document.getElementById("inputone"), <--- the comma doesn't belong here
You’re trying to compare a String with a HTML element here. So what you actually want is
a.innertext
so you compare the two Strings.This uses the event listener ‘input’. The event fires whenever an input is typed into the input box. Whenever a user does so it compares it using regex against the random word.
It appears that you are trying to use an event listener without first attaching it to a DOM object.
Try something like
Alternatively, you can do this in HTML:
Then define
keyupHandler()
in a <script></script> block