Reputation: 121
In this program, I'm generating a random word, getting the input of the user and printing the users' inputted letters in an alert box if the letter exists in the word.
This is where I generate a random word.
var words = ['Quaffle', 'Bludger', 'Pensieve', 'Harry', 'Lupin',
'Butterbeer', 'Polyjuice', 'Patronus', 'Horcrux', 'Voldemort'];
function getRandomWord(){
randomWord = words[Math.floor(Math.random()* words.length)];
wordlength = randomWord.length;
}
And this is function where I get the guess of the user and print it in an alert box along with the correct letters.
function getGuess(){
if(event.keyCode == 13) {
letterGuessed = document.getElementById("inputfield").value;
document.getElementById("inputfield").value = null;
alert(randomWord);
alert(letterGuessed);
r = randomWord.includes(letterGuessed);
if(r == true){
correctletters='';
correctletters = correctletters + letterGuessed;
alert(correctletters);
}
}
}
My problem here is that the correct letter guessed does not concatenate in correctletters
variable. I'm only getting one character which is the letterguessed
variable in the alert box. I even tried using concat
, but I get the same result. Where am I going wrong?
Upvotes: 1
Views: 106
Reputation: 55720
Because, each time you are about to add a new letter, you are resetting the concatenated letters back to an empty string before concatenating the new one.
You should move the following line to somewhere at the initialization logic where you first generate the random word (outside the getGuess
function:
correctletters='';
Upvotes: 2