It is obvious that if the quiz is completed - the user wants to check the score.
Please have a look at the function below.
The function showResults() gathering the answers given by the user by querySelectorAll comand.
(In one of the previous post, I explained the possibility of setting the correct answer inside the database with question)
The variable numCorrect is incremented if the user given correct answer.
Using forEach loop, javaScript gives us the possibility to find selected answer and judge if the answer given by the user was correct or not, then make the decision about increment the score or not.
After the quiz is completed, the script color the correct answers on green, or if answer provided by user was wrong - red.
As a summary of our score the script shows number or correct answers provided divided by total answers.
function showResults(){
// gather answer containers from our quiz
const answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
let numCorrect = 0;
// for each question...
myQuestions.forEach( (currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers[questionNumber];
const selector = 'input[name=question'+questionNumber+']:checked';
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
// if answer is correct
if(userAnswer===currentQuestion.correctAnswer){
// add to the number of correct answers
numCorrect++;
// color the answers green
answerContainers[questionNumber].style.color = 'lightgreen';
}
// if answer is wrong or blank
else{
// color the answers red
answerContainers[questionNumber].style.color = 'red';
}
});
// show number of correct answers out of total
resultsContainer.innerHTML = numCorrect + ' out of ' + myQuestions.length;
}
Web design Hull
Web design services
Freelance web designer
web design blog
IT specialist
Why is the mobile version of the website important?
What it's SSL certificate and how it benefits website?
The most important features for e-commerce store?
Why website does not appear in Google results?
Content marketing is a wide field in which our imagination is the only limitation
What is the guideline when choosing a hosting for the website?
What is worth paying attention to when designing your company's website?
The value of blogging in the terms of website design.
Freelance web designer - Why do you need affordable website?
The ultimate guide how to become freelancer in 2020
6 Features of best UX for web design in 2020
How works Google Assistant. OK Google get started
6 website types which hit the trends in 2020.
10 reasons why CMS need to die in 2020.
What is ZCash and how does this modern cryptocurrency work?
5 Best ways to make money online in 2020. How you can make money online - find something adequate to skills
The comprehensive guide how to become programer in London - 2020.
No comments:
Post a Comment