Fausto Busuito
Application changes
1677ecc
raw
history blame
2.76 kB
let questions = [];
let currentIndex = 0;
let userAnswers = [];
let startTime;
document.getElementById('start-session').addEventListener('click', async () => {
const file = document.getElementById('file').value;
if (!file) return alert("Please select a file");
const response = await fetch('/load_questions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file_name: file })
});
questions = await response.json();
userAnswers = Array(questions.length).fill([]);
startQuiz();
});
function startQuiz() {
document.getElementById('file-selection').style.display = 'none';
document.getElementById('quiz-container').style.display = 'block';
startTime = Date.now();
displayQuestion();
setInterval(updateTimer, 1000);
}
function displayQuestion() {
const question = questions[currentIndex];
document.getElementById('question').innerText = question.question;
const optionsDiv = document.getElementById('options');
optionsDiv.innerHTML = '';
question.options.forEach((option, i) => {
const btn = document.createElement('button');
btn.innerText = option;
btn.className = userAnswers[currentIndex].includes(i) ? 'selected' : '';
btn.addEventListener('click', () => selectAnswer(i));
optionsDiv.appendChild(btn);
});
}
function selectAnswer(optionIndex) {
const currentAnswers = userAnswers[currentIndex];
if (currentAnswers.includes(optionIndex)) {
userAnswers[currentIndex] = currentAnswers.filter(i => i !== optionIndex);
} else {
userAnswers[currentIndex].push(optionIndex);
}
displayQuestion();
}
document.getElementById('next').addEventListener('click', () => {
currentIndex = Math.min(currentIndex + 1, questions.length - 1);
displayQuestion();
});
document.getElementById('prev').addEventListener('click', () => {
currentIndex = Math.max(currentIndex - 1, 0);
displayQuestion();
});
document.getElementById('end-session').addEventListener('click', async () => {
const response = await fetch('/submit_results', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ questions, user_answers: userAnswers })
});
const result = await response.json();
document.getElementById('quiz-container').style.display = 'none';
document.getElementById('results-container').style.display = 'block';
document.getElementById('score').innerText = `Your score: ${result.score.toFixed(2)}%`;
});
function updateTimer() {
const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
document.getElementById('timer').innerText = `Time: ${elapsedTime}s`;
}