document.addEventListener('DOMContentLoaded', () => { const questionElement = document.getElementById('question'); const optionsElement = document.getElementById('options'); const prevButton = document.getElementById('prev'); const nextButton = document.getElementById('next'); const submitButton = document.getElementById('submit'); let questions = []; let currentQuestionIndex = 0; let userAnswers = []; function loadQuestions(data) { questions = data; showQuestion(currentQuestionIndex); } function showQuestion(index) { const question = questions[index]; questionElement.textContent = question.question; optionsElement.innerHTML = ''; question.options.forEach((option, i) => { const optionElement = document.createElement('div'); optionElement.innerHTML = ` `; optionsElement.appendChild(optionElement); }); } prevButton.addEventListener('click', () => { if (currentQuestionIndex > 0) { currentQuestionIndex--; showQuestion(currentQuestionIndex); } }); nextButton.addEventListener('click', () => { if (currentQuestionIndex < questions.length - 1) { currentQuestionIndex++; showQuestion(currentQuestionIndex); } }); submitButton.addEventListener('click', () => { const selectedOptions = Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).map(input => input.value); userAnswers.push({ questionIndex: currentQuestionIndex, answers: selectedOptions }); if (currentQuestionIndex < questions.length - 1) { currentQuestionIndex++; showQuestion(currentQuestionIndex); } else { // Submit the quiz fetch('/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userAnswers) }) .then(response => response.json()) .then(data => { window.location.href = '/results'; }); } }); // Fetch questions from the server fetch('/questions') .then(response => response.json()) .then(data => loadQuestions(data)); });