Interrogative Sentence Quiz
'; javascript Copy code // generate the question HTML quizOutput += '
' + (i+1) + '. ' + questions[i].question + '
';
quizOutput += '' + answerOptions + '
';
}
// display the quiz questions and answers
quizForm.innerHTML = quizOutput;
}
// calculate the quiz score
function calculateScore() {
var score = 0;
var quizForm = document.getElementById("quiz-form");
// loop through each question to check the answers
for (var i = 0; i < questions.length; i++) {
// get the selected answer for the current question
var selector = 'input[name=q' + i + ']:checked';
var userAnswer = quizForm.querySelector(selector).value;
// check if the selected answer is correct
for (var j = 0; j < questions[i].answers.length; j++) {
if (questions[i].answers[j].answer === userAnswer && questions[i].answers[j].isCorrect) {
score++;
break;
}
}
}
// display the quiz score
var scoreOutput = "Your score is " + score + " out of " + questions.length + ".";
document.getElementById("score-output").innerHTML = scoreOutput;
}
// initialize the quiz when the page loads
window.onload = function() {
initializeQuiz();
// add event listener for submit button
document.getElementById("submit-btn").addEventListener("click", function(event) {
event.preventDefault(); // prevent form submission
calculateScore();
});
};
Comments
Post a Comment