0

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>
4
  • 4
    I encourage you to store all the details of the problems in a data structure, such as an array or an object (itself containing objects or arrays). problems = [{text: '1 + 1', answer: 2}, {text: '2^3', answer: 8}]. The count of problems is then problems.length. And you don't have to encode the answer more than once or have a series of if statements (you can just dereference problems[problemNum - 1], but consider starting problemNumber at 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. Commented Apr 25, 2015 at 20:13
  • 2
    Works fine: plnkr.co/edit/Uph8Iv4o81FowGTpdvb0?p=preview Commented Apr 25, 2015 at 20:14
  • Thanks dfsq! Wow, people answer questions quickly on this website. Commented Apr 25, 2015 at 20:33
  • Instead of constantly calling 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. Commented Apr 26, 2015 at 4:31

2 Answers 2

1

Your code seems to work fine. I don't see the input container included in the code snippet you provided. Perhaps you need to make sure the id is correct there? I cleaned up the code a bit:

var div, div2, rightAnswer, 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";
    }
}
<div id="answerDisplay"></div>
<div id="correctOrNot"></div>
<input type="text" id="Input" />

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a way you would rewrite it to use an array of objects as ErikE suggested in his comment.

var questions = [
    {
      q: "4 + 2 * (10 - 3 * 2) / 4 + 8 = ?",
      a: 14
    },
    {
      q: "(6 - 3) * 2 + (3^2 - 5) / 2 = ?",
      a: 8
    },
    {
      q: "5 - 3 + 4^2 / (8 - 4 / 2) = ?",
      a: 6
    },
    {
      q: "5^2 - (6 * 2) * 2 * (5 - 2) = ?",
      a: 3
    }
  ],
  currentQuestion, // the index of the current question will
                   // be stored here so we can look up the answer later
  timerId,
  doc = document,
  elQuestion = doc.getElementById('question')
  elAnswer = doc.getElementById('answer'),
  elUserAnswer = doc.getElementById('user-answer'),
  elCheck = doc.getElementById('check'),

  displayQuestion = function (index) {
    currentQuestion = index;
    elQuestion.textContent = questions[index].q;
  },
  displayRandomQuestion = function () {
    displayQuestion(Math.floor(Math.random() * questions.length));
  },
  removeAnswer = function () {
    timerId = setTimeout(function () {
      elAnswer.textContent = ''
    }, 1000);
  },
  checkAnswer = function () {
    var userAnswer = elUserAnswer.value;

    clearTimeout(timerId);

    // the '' + explicitly converts the .a to a string because userAnswer will be a string
    // using the strict comparison operator (===) is a good habit to get into
    if (userAnswer === '' + questions[currentQuestion].a) { 
      elAnswer.textContent = 'Correct!';
      displayRandomQuestion();
    } else {
      elAnswer.textContent = 'Incorrect, try again';
    }
    removeAnswer();
  };

elCheck.addEventListener('click', checkAnswer, false);
displayRandomQuestion();

Working jsfiddle

Doing it this way is shorter, cleaner and easier to maintain as well. Adding a new question/answer pair is as easy as adding another object to the array. No more copy/pasting if statements and other redundant code. In addition since there is only one place where each action is performed (questions/answers are displayed, the answer is checked, etc) if there is a bug with any of these features there is a single well defined place to look for the bug and you only have to fix it once instead of once for every question in your quiz.

The way I have abstracted lots of the work also makes it easier to extend the code in the future. For instance if you further abstract out the random number code:

getRandomIndex = function () {
  return Math.floor(Math.random() * questions.length);
},

You can alter displayRandomQuestion so it will never repeat the same question twice in a row:

  displayRandomQuestion = function () {
    var index;
    do {
      index = getRandomIndex();
    } while (index === currentIndex);
    displayQuestion(index);
  },

Or even ensure questions never repeat until all the questions have been asked:

  askedIndexes = [],
  displayRandomQuestion = function () {
    var index;
    do {
      index = getRandomIndex();
    } while (askedIndexes.indexOf(index) !== -1);
    if (askedIndexes.length === questions.length - 1) {
      askedIndexes = [];
    }
    askedIndexes.push(index);
    displayQuestion(index);
  },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.