I'm trying to create a game in which an image of a flag is shown and the user must input the correct name of the flag. I've used a random number generator to generate a flag, with each flag having a value assigned to it as the name. How can I fix my function so it can properly compare the user input to the value for the flag object, and thus alert the user if they are correct or incorrect? New to javascript.
Currently, the index.html has a form wherein the user inputs their guess. This guess has the id of "guess". Then the javascript calls this value and is supposed to compare it to the value associated with the flag object. If they match, it should alert the user "correct", if incorrect it should alert "incorrect". However, with my current script, nothing happens when inputting the answer.
HTML:
<div class="imageContainer">
<script language="javascript">
document.write("<div id = flagImage><img src = " + link[random_num].flag + " alt = Flag width = 250px></div>");
</script>
</div>
<div class="guessEnter">
<form onclick="return false">
<input type="text" id="guess" placeholder="Make a guess...">
<div class="submitButton">
<input type="submit" onclick="checkGuess();">
</div>
</form>
</div>
javascript:
/* Pulls random image to display on page */
random_num = (Math.round((Math.random() * 4) + 1));
link = new Array;
link[1] = { flag: "../assets/flagImages/ad.png", value: 'andorra' };
link[2] = { flag: "../assets/flagImages/ae.png", value: 'uae' + 'united arab emirates' }
link[3] = { flag: "../assets/flagImages/af.png", value: 'afghanistan' };
link[4] = { flag: "../assets/flagImages/ag.png", value: 'antigua and barbuda' };
/* Execute function on enter */
guess.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
checkGuess();
}
});
/* Function that compares user input to link value */
const guess = document.getElementById("guess");
function checkGuess() {
if (link[random_num].value.toLowerCase() === guess.value.toLowerCase()) {
alert('You Win!'); //correct guess
} else {
alert('Wrong!'); //wrong guess
}
}