Hi everyone!
Please help me with this exercise!
As the topic mentioned I got an API link https://opentdb.com/api.php?amount=10 and I have to get the data from that API to make a simple quiz with javascript (yes SIMPLE but I can’t figure out how to do it difficult for me). So far my code look like this:
HTML
Challenge QuizChallenge Your Brain!
<div id="quiz"></div>
<button id="submit">Submit Quiz</button>
<div id="results"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="../JS/quizapplikation-script.js"></script>
… And JS
var url = ‘https://opentdb.com/api.php?amount=10’;
var currentQuestion = 0;
$.getJSON(url, function (data) {
var myQuestions = data.results;
for (let i = 0; i < myQuestions.length; i++) {
var question = myQuestions[i].question;
var correctAnswer = myQuestions[i].correct_answer;
var incorrectAnswers = myQuestions[i].incorrect_answers;
var totAnswers = {
correctAnswer,
incorrectAnswers
};
console.log(incorrectAnswers);
}
function buildQuiz() {
const output = [];
myQuestions.forEach((currentQuestion, questionNumber) => {
const answers = [];
for (letter in currentQuestion.totAnswers) {
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.totAnswers[letter]}
</label>`
);
}
output.push(
`<div class="slide">
<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${totAnswers.join("")} </div>
</div>`
);
});
quizContainer.innerHTML = output.join("");
}
function showResults() {
const answerContainers = quizContainer.querySelectorAll(".answers");
let numCorrect = 0;
myQuestions.forEach((currentQuestion, questionNumber) => {
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
if (userAnswer === currentQuestion.correctAnswer) {
numCorrect++;
answerContainers[questionNumber].style.color = "lightgreen";
} else {
answerContainers[questionNumber].style.color = "red";
}
});
resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
}
const quizContainer = document.getElementById(“quiz”);
const resultsContainer = document.getElementById(“results”);
const submitButton = document.getElementById(“submit”);
buildQuiz();
submitButton.addEventListener(“click”, showResults);
})
The problem is I can’t make the answer to showed upp.
As you can see, the questions do appear but not the answers. It looks weird! I don’t understand why? where did I do wrong?
Thanks in advance!
Tho