Guide 3.10: Real Projects
Calculate the Score
When the timer runs out or the user clicks "Submit Exam", we need to grade the paper. Because SdashAPI includes the correct answer directly in the question payload, we can do this instantly on the client side without needing to make another network request.
The submitExam Function
3.10.1Add the submitExam() function to app.js. This function loops through all 40 questions in the array and compares the correct answer property against the user's choice in the userAnswers dictionary.
function submitExam() {
// Stop the timer
clearInterval(timerInterval);
let score = 0;
let attempted = 0;
examQuestions.forEach((q, index) => {
const userAnswer = userAnswers[index];
const correctAnswer = q.answer; // 'a', 'b', 'c', or 'd'
if (userAnswer) {
attempted++;
// Check if correct
if (userAnswer === correctAnswer) {
score++;
}
}
});
const percentage = Math.round((score / examQuestions.length) * 100);
// Transition to result screen
showResultScreen(score, attempted, percentage);
}Wiring the Submit Button
3.10.2Don't forget to attach the function to the manual submit button we created earlier.
document.getElementById('submitExamBtn').addEventListener('click', () => {
const confirmSubmit = confirm("Are you sure you want to submit your exam?");
if (confirmSubmit) {
submitExam();
}
});