-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdummy quiz js.js
92 lines (81 loc) · 2.96 KB
/
dummy quiz js.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
let Questions = [];
const ques = document.getElementById("ques");
async function fetchQuestions() {
try {
const response = await fetch('https://opentdb.com/api.php?amount=10');
if (!response.ok) {
throw new Error('Something went wrong!! Unable to fetch the data');
}
const data = await response.json();
Questions = data.results;
if (Questions.length > 0) {
loadQues();
} else {
ques.innerHTML = `<h5 style='color: red'>Unable to fetch data, Please try again!!</h5>`;
}
} catch (error) {
console.log(error);
ques.innerHTML = `<h5 style='color: red'>${error}</h5>`;
}
}
fetchQuestions();
let currQuestion = 0;
let score = 0;
function loadQues() {
if (Questions.length === 0) {
ques.innerHTML = `<h5>Please Wait!! Loading Questions...</h5>`;
return;
}
const opt = document.getElementById("opt");
let currentQuestion = Questions[currQuestion].question;
currentQuestion = currentQuestion.replace(/"/g, '\"').replace(/'/g, '\'');
ques.innerText = currentQuestion;
opt.innerHTML = "";
const correctAnswer = Questions[currQuestion].correct_answer;
const incorrectAnswers = Questions[currQuestion].incorrect_answers;
const options = [correctAnswer, ...incorrectAnswers];
options.sort(() => Math.random() - 0.5);
options.forEach((option) => {
option = option.replace(/"/g, '\"').replace(/'/g, '\'');
const choicesdiv = document.createElement("div");
const choice = document.createElement("input");
const choiceLabel = document.createElement("label");
choice.type = "radio";
choice.name = "answer";
choice.value = option;
choiceLabel.textContent = option;
choicesdiv.appendChild(choice);
choicesdiv.appendChild(choiceLabel);
opt.appendChild(choicesdiv);
});
}
function loadScore() {
const totalScore = document.getElementById("score");
totalScore.textContent = `You scored ${score} out of ${Questions.length}`;
totalScore.innerHTML += "<h3>All Answers</h3>";
Questions.forEach((el, index) => {
totalScore.innerHTML += `<p>${index + 1}. ${el.correct_answer}</p>`;
});
}
function nextQuestion() {
if (currQuestion < Questions.length - 1) {
currQuestion++;
loadQues();
} else {
document.getElementById("opt").remove();
document.getElementById("ques").remove();
document.getElementById("btn").remove();
loadScore();
}
}
function checkAns() {
const selectedAns = document.querySelector('input[name="answer"]:checked');
if (!selectedAns) {
alert("Please select an answer before proceeding!");
return;
}
if (selectedAns.value === Questions[currQuestion].correct_answer) {
score++;
}
nextQuestion();
}