I am new to javascript and jquery. I am making a simple quiz using jQuery. It is not a multiple choice quiz. The user has to type the answer in the input field. The questions and answers are stored in an array. I am having only one problem that the quiz summary is not showing the correct score. It is showing the score equal to total number of questions each time. I am unable to write the code for it. Most probably the error is in the checkAnswer function.
The code is :
<html>
body>
<div class="start">
<h1> Welcome to English Pupils </h1>
<a class="btn" href="#"> Get Started </a>
</div>
<div class="quiz">
<input type="text" class="input" />
<input type="text" class="output" />
<a class="sub" href="#" onclick="checkAnswer()"> Submit </a>
</div>
<div class="summary">
<h2> Summary Screen </h2>
<p> Congrats you scored x out of y correct ! </p>
<a class="rst" href="#" onclick="restartQuiz()"> Restart Quiz </a>
</div>
</body>
</html>
var questions = [
{
title: "I like cricket.",
answer: "I do not like cricket."
},
{
title: "He is smart.",
answer: "He is not smart."
},
{
title: "She sings well.",
answer: "She does not sing well."
},
{
title: "You are a cheat.",
answer: "You are not a cheat."
},
{
title: "They are coming.",
answer: "They are not coming."
},
];
let score = 0;
let currentQuestion = 0;
$('document').ready(function () {
$('.start a').click(function (e) {
e.preventDefault();
$('.start').hide();
$('.quiz').show();
showQuestion();
});
$('.output').keyup(function (e) {
if (e.keyCode === 13) {
$('.sub').click();
}
});
});
function showQuestion() {
let question = questions[currentQuestion];
$('.input').val(question.title);
}
function checkAnswer() {
let question = questions[currentQuestion];
let out = $('.output').value;
if (out == questions.answer) {
score++;
}
currentQuestion++;
if (currentQuestion >= questions.length) {
showSummary();
} else {
showQuestion();
}
$('.sub').click(function () {
$('.output').val('');
});
}
function showSummary() {
$('.quiz').hide();
$('.summary').show();
$('.summary p').text("Congrats you scored " + score + " out of " + questions.length + " correct !");
}
function restartQuiz() {
$('.summary a').click(function (e) {
e.preventDefault();
$('.summary').hide();
$('.quiz').show();
currentQuestion = 0;
showQuestion();
});
}