|
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 = `<input type="checkbox" id="option${i}" name="option${i}" value="${String.fromCharCode(65 + i)}"> |
|
<label for="option${i}">${option}</label>`; |
|
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 { |
|
|
|
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') |
|
.then(response => response.json()) |
|
.then(data => loadQuestions(data)); |
|
}); |
|
|