Skip to content

Instantly share code, notes, and snippets.

@asha23
Created September 2, 2016 11:48
Show Gist options
  • Save asha23/67dadeabcdc19e8ab57ce7fc57aeecf6 to your computer and use it in GitHub Desktop.
Save asha23/67dadeabcdc19e8ab57ce7fc57aeecf6 to your computer and use it in GitHub Desktop.
Simple Quiz Script
var answers = [ false,true,false,true,true,false,true,true,false,true,true ]
$('form').submit(function(e) {
e.preventDefault();
var $el = $('#results'), errors=getIncorrectAnswers($('form').find('input'),answers);
if (errors.length==0) {
$('tr').removeClass("error");
$el.find("p:not(.error)").text("Congratulations, you got all 11 questions right!");
$el.find("p.error").hide();
} else {
$el.find("p:not(.error)").text("You got "+(11-errors.length)+" out of the 11 questions right.");
$('tr').removeClass("error");
for (var i=0; i<errors.length; i++) {
$('tr[rel='+(errors[i]+1)+']').addClass("error");
}
}
$el.css({ opacity:0, visibility:"visible" }).animate({opacity:1});
var targetOffset = $el.offset().top;
$('html,body').animate({scrollTop: targetOffset}, 1000);
return false;
});
function getIncorrectAnswers($inputs,answers) {
var incorrectAnswers = new Array();
for (var i=0;i<answers.length;i++) {
// IF answer is true
if (answers[i]) {
// If true is checked then answer is correct
if ($inputs.eq(i*2).is(":checked")) {
// do nothing
} else {
incorrectAnswers.push(i);
}
// ELSE answer is false
} else {
if ($inputs.eq((i*2)+1).is(":checked")) {
// do nothing
} else {
incorrectAnswers.push(i);
}
}
}
return incorrectAnswers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment