File size: 2,547 Bytes
d353aa8
 
 
 
 
 
 
 
 
 
 
 
 
 
78447bc
ab240d1
d353aa8
 
 
 
 
 
 
 
 
 
c17c125
78447bc
d353aa8
 
 
 
 
 
78447bc
d353aa8
 
 
 
 
 
78447bc
d353aa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78447bc
 
d353aa8
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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 {
            // 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));
});