Locked lesson.
About this lesson
Exercise files
Download this lesson’s related exercise files.
Output the Result.docx59.6 KB Output the Result - Solution.docx
60.5 KB
Quick reference
Output the Result
Let's check our user answer against the correct answer and output the result.
When to use
Whenever a user submits their answer, we need to check the answer against the correct answer.
Instructions
Let's take a look at our final code:
<html>
<head>
<title>Addition Flashcards</title>
<script>
var number1 = Math.floor((Math.random() * 10) + 1);
var number2 = Math.floor((Math.random() * 10) + 1);
var correctAnswer = number1 + number2;
var output;
</script>
</head>
<body>
<h1>Addition Flashcards</h1>
<h1 id="numbers">
<script>
document.write(number1 + " + " + number2);
</script>
</h1>
<input id="answer">
<button type="button" onclick="userAnswer();">Submit Answer</button>
<button type="button" onclick="nextCard();">Next Card</button>
<p id="output"></p>
<script>
function userAnswer(){
var userAnswer = document.getElementById("answer").value;
if (isNaN(userAnswer)) {output = "Hey! That's not a number, try again!";} else {
if (userAnswer == correctAnswer) {output = "Correct! " + number1 + " + " + number2 + " = " + correctAnswer;} else {output = "Wrong! " + number1 + " + " + number2 + " is not " + userAnswer;}
}
document.getElementById("output").innerHTML = output;
}
function nextCard(){
document.getElementById("output").innerHTML = "";
document.getElementById("answer").value = "";
number1 = Math.floor((Math.random() * 10) + 1);
number2 = Math.floor((Math.random() * 10) + 1);
correctAnswer = number1 + number2;
document.getElementById("numbers").innerHTML = (number1 + " + " + number2);
}
</script>
</body>
</html>
Hints & tips
- Checking the user's answer seems like a job for an If/Else statement!
Lesson notes are only available for subscribers.