JS Quiz v.02 (wk 5-6)
In progress
by zenstunna
HTML
<h1>Quiz App</h1>
<p id='question'>Question</p>
<input type='radio' name='answers' value=0><span id="ans0"> Answer 0</span>
<br />
<br />
<input type='radio' name='answers' value=1><span id="ans1"> Answer 1</span>
<br />
<br />
<input type='radio' name='answers' value=2><span id="ans2"> Answer 2</span>
<br />
<br />
<input type='radio' name='answers' value=3><span id="ans3"> Answer 3</span>
<br />
<br />
<button type="submit" id="button">Submit</button>
JavaScript
var questions = [{
question: "What is my name?",
choices: ["David", "Dorian", "Bill", "George"],
correctAnswer: 1
}, {
question: "What is my age?",
choices: ["20", "25", "30", "35"],
correctAnswer: 2
}, {
question: "What is my favorite color?",
choices: ["blue", "green", "orange", "red"],
correctAnswer: 0
}, {
question: "How tall am I?",
choices: ["5-10", "5-11", "6-0", "6-1"],
correctAnswer: 2
}, {
question: "Which OS is my favorite?",
choices: ["Window 7", "Windows 8", "Linux", "Mac OS"],
correctAnswer: 3
}];
$(document).ready(function () {
var maxQuestions = questions.length;
var numRight = 0;
var counter = 0;
// display first question
$('#question').text(questions[counter].question);
$('#ans0').text(questions[counter].choices[0]);
$('#ans1').text(questions[counter].choices[1]);
$('#ans2').text(questions[counter].choices[2]);
$('#ans3').text(questions[counter].choices[3]);
$('button').on('click', function () {
var answer = ($('input[name="answers"]:checked').val());
// increment score if right
if (answer == questions[counter].correctAnswer) numRight++;
counter++;
if (counter >= maxQuestions) {
document.write("Quiz is over. You got ", numRight, " out of ", maxQuestions);
return;
}
// Show next question
$('#question').text(questions[counter].question);
$('#ans0').text(questions[counter].choices[0]);
$('#ans1').text(questions[counter].choices[1]);
$('#ans2').text(questions[counter].choices[2]);
$('#ans3').text(questions[counter].choices[3]);
});
});