-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathquiz.js
More file actions
81 lines (63 loc) · 2.17 KB
/
quiz.js
File metadata and controls
81 lines (63 loc) · 2.17 KB
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
function generateQuiz(questions, quizContainer, resultsContainer, submitButton){
function showQuestions(questions, quizContainer){
// we'll need a place to store the output and the answer choices
var output = [];
var answers;
// for each question...
for(var i=0; i<questions.length; i++){
// first reset the list of answers
answers = [];
// for each available answer to this question...
for(letter in questions[i].answers){
// ...add an html radio button
answers.push(
'<label>'
+ '<input type="text" class="form-control form-control-sm" name="question'+i+'" value="">'
//+ letter + ': '
+ questions[i].answers[letter]
+ '</label>'
);
}
// add this question and its answers to the output
output.push(
//'<div class="question">' + questions[i].question + '</div>'
/*+*/ '<pre></pre><div class="answers">' + answers.join('') + '</div>'
);
}
// finally combine our output list into one string of html and put it on the page
quizContainer.innerHTML = output.join('');
quizContainer.className = "form-group";
submitButton.className = "btn btn-success form-group";
}
showQuestions(questions, quizContainer);
function showResults(questions, quizContainer, resultsContainer){
// gather answer containers from our quiz
var answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
var userAnswer = '';
var correct = false;
// for each question...
for(var i=0; i<questions.length; i++){
// find selected answer
userAnswer = (answerContainers[i].querySelector('input[name=question'+i+']')||{}).value;
// if answer is correct
if(userAnswer===questions[i].correctAnswer){
// add to the number of correct answers
correct=true;}
}
// show number of correct answers out of total
if (correct){
var message = "Correct!";
var type = "alert alert-success"}
else {
var message = "Try Again.";
var type = "alert alert-danger"}
resultsContainer.innerHTML = message;
resultsContainer.className = type;
resultsContainer.setAttribute("role","alert")
}
// when user clicks submit, show results
submitButton.onclick = function(){
showResults(questions, quizContainer, resultsContainer);
}
}