For some reason, the div tags are not displayed in the webpage when the program is run. I tested every other component and have figured out that the problem is that the setting of the value of the div tags is in an if statement. The only problem is that I do not know how to fix the problem and still have the program run the way I want it to.
<div id="answerDisplay"></div>
<div id="correctOrNot"></div>
<script>
var div
var div2
var rightAnswer
var problemNum =Math.floor((Math.random() * 3) + 1);
if (problemNum == 1){
rightAnswer = 14;
div = document.getElementById("answerDisplay");
div.textContent = "4 + 2 * (10 - 3 * 2) / 4 + 8 = ?";
}
else if (problemNum == 2){
rightAnswer = 8;
div = document.getElementById("answerDisplay");
div.textContent = "(6 - 3) * 2 + (3^2 - 5) / 2 = ?";
}
else if (problemNum == 3){
rightAnswer = 6;
div = document.getElementById("answerDisplay");
div.textContent = "5 - 3 + 4^2 / (8 - 4 / 2) = ?";
}
else if (problemNum == 4){
rightAnswer = 3;
div = document.getElementById("answerDisplay");
div.textContent = "5^2 - (6 * 2) * 2 * (5 - 2) = ?";
}
function checkRightAnswer (){
var answer = document.getElementById('Input').value
if (problemNum == 1 && answer == 14){
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum =Math.floor((Math.random() * 3) + 1);
}
else if (problemNum == 2 && answer == 8){
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum =Math.floor((Math.random() * 3) + 1);
}
else if (problemNum == 3 && answer == 6){
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum =Math.floor((Math.random() * 3) + 1);
}
else if (problemNum == 4 && answer == 3){
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum =Math.floor((Math.random() * 3) + 1);
}
else {
div2 = document.getElementById("correctOrNot");
div2.textContent = "Incorrect, try again";
}
}
</script>
problems = [{text: '1 + 1', answer: 2}, {text: '2^3', answer: 8}]. The count of problems is thenproblems.length. And you don't have to encode the answer more than once or have a series of if statements (you can just dereferenceproblems[problemNum - 1], but consider startingproblemNumberat 0 instead of 1). The way you've currently coded everything is unnecessarily repetitive. In JavaScript it's also probably best to prefer single quotes.getElementById, call it once at the beginning of the code block and store it in a variable and access it via that variable everywhere you need it. It will make your code more DRY, which will reduce the amount of code that needs to be downloaded, make it harder to introduce new bugs, and make it easier to maintain in the future. It will also make your code run faster; the DOM is slow, the less you touch the DOM, the faster your code will run.