Home > database >  Why is if...else statement only compares single word values?
Why is if...else statement only compares single word values?

Time:10-04

I am making a quiz app that will basically fetch the questions and answers from an API and display it to the webpage. It works fine, but the error handling isn't working. I have a if...else statement that will check if a user has selected the right answer, and if they did, play a sound and display "Nice job" to the user. If they did not, then tell the user that they need to try again. The behavior that I'm getting is very weird. Sometimes when I have chose the correct answer, it says it is not correct. It happens when there is spaces within the answer. For single words such as "true", "false" or "Hello" works fine. I logged the answer to the console stored in a variable called answer_container, when I logged it to the console, the answer and my choice are exactly the same. I have tried using === and == operators to see if that would work, but the result is the same. I have posted the full code including my HTML so that you can see what it is happening. Note it took me couple of tries to get the weird behavior to display.

Here is what I have tried:

var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
  document.getElementById('next').disabled = true;
  document.getElementById('msgSuccess').innerHTML = '';
  document.getElementById('check').disabled = false;
  document.getElementById('showAnswer').disabled = false;
  var getData = await fetch(url);
  var toJS = await getData.json();
  answer_container = toJS.results[0].correct_answer;
  var container = [];
  for (var i = 0; i < toJS.results[0].incorrect_answers.length; i  ) {
    container.push(toJS.results[0].incorrect_answers[i]);
  }
  container.push(toJS.results[0].correct_answer);
  container.sort(func);

  function func(a, b) {
    return 0.5 - Math.random();
  }
  html_container = [];
  container.forEach(function(choices) {
    html_container.push(`
<option value=${choices}>
${choices}
</option>
`)
  });
  document.getElementById('choice').innerHTML = html_container.join();
  if (toJS.results[0].type === 'boolean') {
    document.getElementById('type').innerHTML =
      `This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
  } else {
    document.getElementById('type').innerHTML =
      `This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
  }
}
fetchData();
showAnswer.addEventListener('click', function() {
  document.getElementById('answer_element').innerHTML = "The answer to this question is "   answer_container;
  document.getElementById('answer_element').style.display = "block";
  setTimeout(function() {
    document.getElementById('answer_element').style.display = "none";
  }, 3000);
});

function check() {
  var select_answer = document.getElementById('choice').value;
  var audio = document.getElementById('audio');
  if (select_answer == answer_container) {
    score  ;
    document.getElementById('showAnswer').disabled = true;
    document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
    document.getElementById('next').disabled = false;
    document.getElementById('check').disabled = true;
    audio.play();
    console.log(answer_container);
  }
  if (select_answer != answer_container) {
    score--;
    document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
    document.getElementById('next').disabled = true;
    console.log(answer_container);
  }
}
<!DOCTYPE html>
<html>

<head>
  <title>
    Quiz App
  </title>
</head>

<body>
  <div id="type">
  </div>
  <label>
Select Your Answer...
</label>
  <select id="choice">
  </select>
  <button id="showAnswer">
Show Answer
</button>
  <p id="answer_element">
  </p>
  <button onclick="check()" id="check">
Check
</button>
  <p id="msgSuccess">
  </p>
  <button id="next" onclick="fetchData()">
Next Question
</button>
  <audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>

</html>

CodePudding user response:

You're using the expression select_answer == answer_container to determine if the choice is the correct answer.

select_answer comes from the value attribute of the option you've selected. However, when an answer value contains whitespace, HTML interprets only up to the first whitespace as the "value". When answers like North America come up, the option's value attribute is only North.

When generating your options in your HTML, you need to properly encapsulate them in double quotes ", like so:

html_container.push(`
    <option value="${choices}">
        ${choices}
    </option>
`)

Tangential, but it would probably be cleaner if you generated your elements with enter image description here

You need quotes in the HTML option to preserve white space.

<option value=${choices} <- picks the first word
<option value="${choices}" <- allows the whole string with spaces

var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
  document.getElementById('next').disabled = true;
  document.getElementById('msgSuccess').innerHTML = '';
  document.getElementById('check').disabled = false;
  document.getElementById('showAnswer').disabled = false;
  var getData = await fetch(url);
  var toJS = await getData.json();
  console.log(toJS)
  answer_container = toJS.results[0].correct_answer;
  var container = [];
  for (var i = 0; i < toJS.results[0].incorrect_answers.length; i  ) {
container.push(toJS.results[0].incorrect_answers[i]);
  }
  container.push(toJS.results[0].correct_answer);
  container.sort(func);
  function func(a, b) {
return 0.5 - Math.random();
  }
  html_container = [];
  container.forEach(function (choices) {
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
  });
  document.getElementById('choice').innerHTML = html_container.join();
  if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
  `This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
  }
  else {
document.getElementById('type').innerHTML =
  `This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
  }
}
fetchData();
showAnswer.addEventListener('click', function () {
  document.getElementById('answer_element').innerHTML = "The answer to this question is "   answer_container;
  document.getElementById('answer_element').style.display = "block";
  setTimeout(function () {
document.getElementById('answer_element').style.display = "none";
  }, 3000);
});
function check() {
  var select_answer = document.getElementById('choice').value;
  var audio = document.getElementById('audio');
  console.log(select_answer, answer_container)
  if (select_answer == answer_container) {
score  ;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
  }
  if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
  }
}
<!DOCTYPE html>
<html>

<head>
  <title>
Quiz App
  </title>
</head>

<body>
  <div id="type">
  </div>
  <label>
Select Your Answer...
  </label>
  <select id="choice">
  </select>
  <button id="showAnswer">
Show Answer
  </button>
  <p id="answer_element">
  </p>
  <button onclick="check()" id="check">
Check
  </button>
  <p id="msgSuccess">
  </p>
  <button id="next" onclick="fetchData()">
Next Question
  </button>
  <audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
  </audio>
</body>

</html>

  • Related