New on DHTMLGoodies.com:

DHTML Chess Wordpress Plugin (Beta) . Participate in the beta testing of the DHTML Chess for WordPress plugin, and receive a free Commercial License worth USD99.

Javascript quiz maker

Demo

Bookmark and Share

Overview

This script enables you to create quiz forms on your web nice and easily.

Licensing

This script is free and licensed under LGPL. Commercial licenses are also available.

Download

Files in package:

  • js/dg-quiz-maker.js - Main javascript file for the widget
  • js/external/* - Mootools library used by the script

Demo

Configuration

Include javascript files

First of all, you'll need to include the two javascript files mootools-1.2.4-core-yc.js and dg-quiz-maker.js

Example:

<script src="/scripts/quiz-maker/js/external/mootools-1.2.4-core-yc.js"></script>
<script src="/scripts/quiz-maker/js/dg-quiz-maker.js"></script>

Configure the DG.QuizMaker object

The code below shows you an example on how to configure the quiz maker

var questions = [
   {
     label : 'What is the capital of Norway ?',
     options : ['Stockholm', 'Oslo', 'Copenhagen'],
     answer : ['Oslo']
     forceAnswer : true
   },
   {
     label : 'World champion, WC South Africa 2010 ?',
     options : ['Brazil', 'Netherlands', 'Spain'],
     answer : ['Spain']
   },
   {
     label : 'Prime minister(s) of England during World War II ?',
     options : ['Clement Attlee', 'Sir Winston Churchill', 'Neville Chamberlain', 'Sir Anthony Eden'],
     answer : [1,2] // refers to the second and third option
   }
,
   {
     label : 'United States has how many states',
     options : ['49','50','51'],
     answer : ['50']
   },
   {
     label : 'A crocodile is a member of which family ?',
     options : ['amphibian','reptile', 'vermin'],
     answer : ['reptile']
   },
   {
     label: 'In which year did Atlanta(US) arrange the summer olympics ?',
     options : ['1992','1996','2000'],
     answer :['1996']
   }
]

function showAnswerAlert() {
   $('error').set('html', 'You have to answer before you continue to the next question');
}
function clearErrorBox() {
   $('error').set('html','');
}

var quizMaker = new DG.QuizMaker({
   questions : questions,
   el : 'questions',
   listeners : {
   'finish' : showScore,
   'missinganswer' : showAnswerAlert,
   'sendanswer' : clearErrorBox
}
});

The question object

I have created a "questions" array. Each element in the array represents a question.

  • label representes the label for this question
  • options represents the different available answering options
  • answer represents the correct answers. Answers can be either a text equal to the correct option, or the index of the correct answer, example in the code above: prime minister of england. Correct answers are the second and third option, i.e. index 1 and 2
  • forceAnswer can be used to force an answer on a specific question. forceAnswer can also be added directly to the constructor if you want to force an answer to all questions
  • forceCorrectAnswer can be used to force a correct answer on a specific question. forceCorrectAnswer can also be added directly to the constructor if you want to force correct answers to all questions

Constructor parameters

The constructor accepts the following parameters:

  • questions: A reference to the question array.
  • el: The element on your html page(example a <div>) where the questions will be displayed
  • listeners: List of functions to call when specific events occurs. See list below for valid events

Events

The script implements these events:

  • finished: Fires when the quiz is finished. Example: in the code above, I have specified that a function called "showScore" should be called when the quiz is finished

  • sendanswer: Fires when the user clicks the answer button.
  • missinganswer: Fires when the user clicks the answer button and answer is missing.
  • wrongAnswer: Fires when config option forceCorrectAnswer is set to true and wrong answer has been sent.

Public methods

There is one very important method in this script, and that is the getScore() method.

This method should be called after the user has finished the quiz. It will return an object like this:

{
  numCorrectAnswers : 4
  numQuestions : 6
  percentageCorrectAnswers : 67
  incorrectAnswers : [
    {
      questionNumber : 1
      label : What is the capital of Norway
      correctAnswer : Oslo
      userAnswer : Copenhagen
  },
    {
      questionNumber : 3
      label : Prime minister of england during WWII
      correctAnswer : Churchill, Chamberlain
      userAnswer : Churchill, Eden
  }
]
}

You can use this object to show your custom user response for the quiz. Take a look at the demo for an example of how this has been implemented

Comments

Paradigm Productions
Great script! Any way to have multiples questions on a single page? Thanks!
Paradigm Productions at 10:30AM, 2011/02/28.
RBeezy
doesn't appear to be working in IE7
RBeezy at 08:30AM, 2011/03/30.
Admin comment
DHTMLGoodies
Thanks Rbezy,

This is actually a well known problem with IE6 and IE7 when you create radio buttons dynamically and give them a name afterwards.

I have fixed it and uploaded the download zip file.

Thanks again.
DHTMLGoodies at 09:15AM, 2011/03/30.
Samuel Vargian
Great script! that what I was looking for long time

Thanks!
Samuel Vargian at 01:23AM, 2011/08/19.
workerBee
Hey great script , works a treat. I was wondering what would be the best/simplest way to implement another field, that can elaborate the answers better to the user, so when showscore fires it is displayed along with the correct answer. any insight would be great!. Thanks!.
workerBee at 03:11PM, 2011/09/07.
Tom Edwards
JavaScript Quiz Maker software that you have for download is impossible use, the information and JavaScript is all over the page on notepad and not organized so that I can use it.

Can you help me get a better organized copy of JavaScript Quiz Maker to download?

Please send reply!
Tom Edwards
Tom Edwards at 02:30PM, 2011/12/25.
Andi
can I make a question that users can fill the answer by their own text?
Andi at 07:27AM, 2012/04/23.
Subhash
Hi,
Thanks for the script. Is there any way you can create a MS access DB where all questions ,answers and employee details get stored.and also if you can disable the view source and back option.
Subhash at 12:16PM, 2012/04/25.
Ted
Just a dumb question--
Could a savvy user with Firebug or Chrome do "inspect element" on this quiz and see the correct answers in the javascript?
thanks-
T
Ted at 02:24PM, 2012/05/04.
Albert
Hello,

I need some urgent help. The script doesn't seem to work in IE 9, it only shows the first question (without any possible answers). You can easily see that if you access this same page with IE 9, the demo has this same problem. Is there any way to fix this? Thank so much in advance!
Albert at 10:11AM, 2012/05/14.
sean
very nice thank you very much!
sean at 05:30PM, 2012/07/14.
sean
Is there anyway to have a hyperlink after the end of the quiz?
sean at 01:35PM, 2012/07/15.
Michael Victoriano
Hi,
Is there a way to put different images to some pages (if needed) to supplement the questionaires?
Michael Victoriano at 08:30AM, 2012/07/30.
Allan
<a href="#comment1965">Michael Victoriano wrote:</a>
Hi,
Is there a way to put different images to some pages (if needed) to supplement the questionaires?


Im looking the same thing have you had any luck?
Allan at 02:42AM, 2012/08/07.
zoli
script not work in IE 9
zoli at 09:25AM, 2012/08/23.
David Horan
This is a fantastic code - the quiz is really useful.
I was wondering how one can change to font-size of the finished quiz.
Many thanks in advance,
David
David Horan at 05:23PM, 2012/11/09.
Ross
Is there any way to force the user to enter the correct answer before moving onto the next question? Also any news on this working in IE9?
Ross at 05:38AM, 2012/11/13.
Admin comment
DHTMLGoodies
David,

The final score page is rendered inside a div with class name "result". So you can modify the fonts with css. Example:

<style type="text/css">
.score{
color:blue;
font-weight:bold;
font-size:14px;
}
</style>

Ross,

The IE9 problem has been fixed by updating to newest Mootols library.

I have implemented a new option "forceCorrectAnswer" which will give you the feature you requested. Example:

var quizMaker = new DG.QuizMaker({
   questions : questions,
   el : 'questions',
   forceCorrectAnswer:true,
   listeners : {
     'finish' : showScore,
     'missinganswer' : showAnswerAlert,
     'sendanswer' : clearErrorBox,
     'wrongAnswer' : showWrongAnswer
   }
});

when forceCorrectAnswer is set to true, you will not be able to move to next question until you have answered correctly on the current one. A "wrongAnswer" event will be fired.

As you can see in the code above, I have added a listener to the "wrongAnswer" event. It will call the function showWrongAnswer which looks like this:

function showWrongAnswer(){
document.id('error').set('html', 'Wrong answer, Please try again');
}

DHTMLGoodies at 04:37AM, 2012/11/14.
RocketSMS
A couple of hints ...

In files for download there is a link to dg-count-down.js that is not provided and not needed in quiz-maker.html

Also there are other classes of interest which are needed for formatting:

dg-question-option
dg-answer-button-container

I added for my own use dg-score, dg-score-span, and dg-summary-label
RocketSMS at 05:37PM, 2013/01/06.
mloganathan
dear friend, your quiz maker script which is really useful. one more thing, how to add random method 6 0ut of 10 question.
mloganathan at 09:56PM, 2013/01/07.
mloganathan
dear friend, your quiz maker script which is really useful. one more thing, how to add random method 6 0ut of 10 question.
mloganathan at 09:24AM, 2013/01/14.
DveD
Great code, but... It seems that ShowAnswerAlert doesn't work properly. It works only with a first question, missing answer in the others is ignored without alert. Thanks for your reply...DveD
DveD at 07:51AM, 2013/03/11.
DveD
Sorry, I found it...

DveD at 11:32AM, 2013/03/11.
steve
Thank you for this code, but I cannot get it to work. On the designer-developer scale, I am clearly on the designer end of the spectrum, albeit moving toward the developer end.

I copied the JS code above, put it in the head of the HTML code, downloaded the files and located them appropriately, but . . . Nothing.

I am sure it is something simple. Can you help me. Thank you!
steve at 01:07AM, 2013/03/17.
Adeyinka Ogunkoya
Hi, how can i capture the final score and store in a database.

I captured the result div in a string : $str="<div id=\"result\"></div>";
But it doesn't store the result.

Please help
Adeyinka Ogunkoya at 10:33AM, 2013/04/06.
Javier Granda

Really useful script. Thanks!. I really want to be able to add images to some of the questions. Does anybody know how to accomplish this?? I would be very grateful

Thank you!
Javier Granda at 09:11AM, 2013/09/03.
Javier Granda
<a href="#comment2001">Allan wrote:</a>
<a href="#comment1965">Michael Victoriano wrote:</a>
Hi,
Is there a way to put different images to some pages (if needed) to supplement the questionaires?


Im looking the same thing have you had any luck?


I solved it:

You have to add this function on the dg-quiz-maker.js file:

_addImageElement : function() {
var elimg = new Element('img');
elimg.addClass('dg-question-image');
elimg.id='imagen';
elimg.src=this._getCurrentQuestion().image;
elimg.set('html');
document.body.appendChild(elimg);

},

Later you have to edit this function to clear every image on every question:

_sendAnswer : function() {

var answer = this._getAnswersFromForm();

this.fireEvent('sendanswer', this)
var currentQuestion = this._getCurrentQuestion();
if((this.config.forceAnswer || currentQuestion.forceAnswer) && answer.length == 0) {
this.fireEvent('missinganswer', this);
return false;
}

this.user.answers[this.internal.questionIndex] = answer;

if(!this._hasAnsweredCorrectly(this.internal.questionIndex) && (this.forceCorrectAnswer || currentQuestion['forceCorrectAnswer'])){
this.fireEvent('wrongAnswer', this);
return false;
}


this.internal.questionIndex++;

if (this.internal.questionIndex == this.internal.questions.length) {
this._clearEl();
this.fireEvent('finish');
}
else {
var q_image= document.getElementById('imagen');
q_image.destroy();
this._displayQuestion();
}
},

And finnally add it like this on the html:

label : '¿Cuál es la velocidad máxima en ciudad para un automóvil en calles?',
image: '../img/download.jpeg',
options : ['a. 40km/h.', 'b. 50km/h', 'c. 60km/h.'],
answer : ['b. 50km/h'],
forceAnswer : true
Javier Granda at 10:35AM, 2013/09/03.
mickael
Hello
i would like know how can i do a quiz with random question.

Thanks a lot
mickael at 02:59AM, 2013/09/05.
Javier Granda
<a href="#comment4508">mickael wrote:</a>
Hello
i would like know how can i do a quiz with random question.

Thanks a lot


Use this function:

function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};

And then call it:

var quizMaker = new DG.QuizMaker({
questions : shuffle(questions),
el : 'questions',
forceCorrectAnswer:false,
listeners : {
'finish' : showScore,
'missinganswer' : showAnswerAlert,
'sendanswer' : clearErrorBox,
'wrongAnswer' : showWrongAnswer
}
});
Javier Granda at 11:39AM, 2013/09/06.
Javier Granda
<a href="#comment4508">mickael wrote:</a>
Hello
i would like know how can i do a quiz with random question.

Thanks a lot


Use this function:

function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};

And then call it:

var quizMaker = new DG.QuizMaker({
questions : shuffle(questions),
el : 'questions',
forceCorrectAnswer:false,
listeners : {
'finish' : showScore,
'missinganswer' : showAnswerAlert,
'sendanswer' : clearErrorBox,
'wrongAnswer' : showWrongAnswer
}
});
Javier Granda at 11:40AM, 2013/09/06.
Poras
Great script! Any way to have multiples questions on a single page? Thanks!
Poras at 08:05AM, 2013/09/15.
Peder Wessel
<a href="#comment4507">Javier Granda wrote:</a>
<a href="#comment2001">Allan wrote:</a>
<a href="#comment1965">Michael Victoriano wrote:</a>
Hi,
Is there a way to put different images to some pages (if needed) to supplement the questionaires?


Im looking the same thing have you had any luck?


I solved it:

You have to add this function on the dg-quiz-maker.js file:

_addImageElement : function() {
var elimg = new Element('img');
elimg.addClass('dg-question-image');
elimg.id='imagen';
elimg.src=this._getCurrentQuestion().image;
elimg.set('html');
document.body.appendChild(elimg);

},

Later you have to edit this function to clear every image on every question:

_sendAnswer : function() {

var answer = this._getAnswersFromForm();

this.fireEvent('sendanswer', this)
var currentQuestion = this._getCurrentQuestion();
if((this.config.forceAnswer || currentQuestion.forceAnswer) && answer.length == 0) {
this.fireEvent('missinganswer', this);
return false;
}

this.user.answers[this.internal.questionIndex] = answer;

if(!this._hasAnsweredCorrectly(this.internal.questionIndex) && (this.forceCorrectAnswer || currentQuestion['forceCorrectAnswer'])){
this.fireEvent('wrongAnswer', this);
return false;
}


this.internal.questionIndex++;

if (this.internal.questionIndex == this.internal.questions.length) {
this._clearEl();
this.fireEvent('finish');
}
else {
var q_image= document.getElementById('imagen');
q_image.destroy();
this._displayQuestion();
}
},

And finnally add it like this on the html:

label : '¿Cuál es la velocidad máxima en ciudad para un automóvil en calles?',
image: '../img/download.jpeg',
options : ['a. 40km/h.', 'b. 50km/h', 'c. 60km/h.'],
answer : ['b. 50km/h'],
forceAnswer : true



Javier - I like your code. But I am struggling to get it to work to add a picture. The question is appearing, but not the picture?

I have a test picture called "test.jpg" which is in the same folder as my HTML file. I inserted the code in the JS file as you suggested and have the following code in the HTML:

var questions = [
{
label : 'Test question?',
image: 'test.jpg',
options : ['2%', '4%', '6%'],
answer : ['4%'],
forceAnswer : true
},

Would appreciate your support! Thanks!
Peder Wessel at 11:20AM, 2013/10/20.
Sri
please correct the code am getting error while displaying score
<code>
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" lang="en">
<head>
<meta http-equiv="default-style" content="text/html; charset=utf-8"/>
<title>LNS</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

$(function() {


$(".ans").click(function(e){
var res = $(this).attr("data-type")
var clickCounter = $("#count").data("clickCounter");
clickCounter = (clickCounter + res);
$("#count").data("clickCounter", res);
$("#count").html(clickCounter);
});

$("#answer1_q1").click(function() {
$("#answers_q1").html('Correct');
});
$("#answer2_q1").click(function() {
$("#answers_q1").html('Wrong');
});

$("#answer1_q2").click(function() {
$("#answers_q2").html('Correct');
});
$("#answer2_q2").click(function() {
$("#answers_q2").html('Wrong');
});

$("#answer1_q3").click(function() {
$("#answers_q3").html('Correct');
});
$("#answer2_q3").click(function() {
$("#answers_q3").html('Wrong');
});
/**/

});
</script>
</head>
<body>
<style type="text/css">
.hide{
display:none;
}
</style>

<div id="Question1">Question 1
<div id="answers_q1">
<div id="answer1_q1" class="ans" data-type="1">answer 1</div>
<div id="answer2_q1" class="ans" data-type="0">answer 2</div>
</div>
</div>
<br />
<div id="Question2">Question 2
<div id="answers_q2">
<div id="answer1_q2" class="ans" data-type="1">answer 1</div>
<div id="answer2_q2" class="ans" data-type="0">answer 2</div>
</div>
</div>
<br />
<div id="Question3">Question 3
<div id="answers_q3">
<div id="answer1_q3" class="ans" data-type="1">answer 1</div>
<div id="answer2_q3" class="ans" data-type="0">answer 2</div>
</div>
</div>
<br />
<div id="total">Total Results
<div id="answers_total">
You have <span id="count"></span> correct answers out of total 3 Questions!!!
</div>
</div>
</body>
</html>
Sri at 03:29AM, 2013/11/13.
Satender Sharma
Thanks! Great work.
I want to add a timer and question pallet (where question numbers are mentioned, so user can switch to any question during exam). Any help would be appreciable.


Satender Sharma at 08:09AM, 2014/01/24.
Will_C
Is there any way the entire page could reload at the user input of next? Basically I am looking for a one question per page script like this but when the user selects next it reloads the entire page.
Will_C at 06:22PM, 2014/04/21.
Brian
Love the code. But I can get the image code above working. Any help or a link to a working model would be HUGELY appreciated!
Brian at 03:07PM, 2014/07/22.
sam
Is posible send email results?
sam at 01:13PM, 2014/07/31.
ryan
how to edit the submit button..css cant do it .dg-answer-button-container
ryan at 11:09AM, 2014/08/18.
dadz
Great code!thanks, btw how to set a timer?
dadz at 02:10AM, 2014/08/27.
meraj
Great Work!!!Thanks a lot...

<p>Is there any way to move directly between questions...say i want to move to question 3 directly from question 1 and so on
meraj at 11:47PM, 2014/10/13.
SCOTTR
Love the script, using the randomizer function posted above with it. I'm curious if there is a way to make this script randomly pull a pre-defined number of questions thou? Like say I have 250 questions loaded and I want it to randomly select 150 of those to populate the exam with?

Many thanks!
SCOTTR at 09:20AM, 2015/01/07.
Joram Kimata
Hello!

Nice script but i wonder on how to create questions and save them to the database any soln i will appreciate
Joram Kimata at 10:49AM, 2015/04/01.
Serge
Hello guys

I am trying to do the quiz. Is it possible to create a file after finishing the quiz and put there following information, like:

1) question 1
What is the capital of Great Britain
> London - CORRECT

2) question 2
What is the capital of France
> Lyon - INCORRECT

etc.
thank you in advance.
Serge at 09:20AM, 2015/06/16.
Max Demars
Is it possible to have version without mootools? Just pure AMD library.
Max Demars at 07:17AM, 2015/10/02.
Max Demars
Am I wrong? It seems that you use mootools only to extend the Class object? If yes, it would be easy to exclude mootols dependancy.
Max Demars at 07:21AM, 2015/10/02.
saidihasan
how to add images, in this script ?
saidihasan at 03:33AM, 2016/01/15.
nen gawker
Awesome script. Thank you.

How many questions it can load? Because right now I can only add up to 8..is javascript var has limits? please advise..
nen gawker at 04:04PM, 2016/02/03.
rajesh
how to add count time .js
<script type="text/javascript" src="js/dg-count-down.js"></script>
rajesh at 01:43AM, 2016/02/19.
rajesh
Adding Image code is right process? its not working..
if(!window.DG) {
window.DG = {};
};

DG.QuizMaker = new Class( {
Extends : Events,

validEvents : ['start','sendanswer', 'correctanswer','wronganswer', 'finish','missinganswer','wrongAnswer'],

config: {
seconds: null,
forceAnswer : false
},

html : {
el : null
},

internal : {
questionIndex : 0,
questions : null,
labelAnswerButton : 'Answer'
},

user : {
answers : []
},

forceCorrectAnswer:false,

initialize : function(config) {
if(config.el) {
this.html.el = config.el;
}
if(config.forceAnswer) {
this.config.forceAnswer = config.forceAnswer;
}
if(config.forceCorrectAnswer !== undefined)this.forceCorrectAnswer = config.forceCorrectAnswer;
if(config.labelAnswerButton) {
this.internal.labelAnswerButton = config.labelAnswerButton;
}

this.internal.questions = config.questions;

if(config.listeners) {
for(var listener in config.listeners) {
if(this.validEvents.indexOf(listener)>=0) {
this.addEvent(listener, config.listeners[listener]);
}
}
}
},

_displayQuestion : function() {
this._clearEl();
this._addQuestionElement();
this._addAnsweringOptions();
this._addAnswerButton();
},

_addQuestionElement : function() {
var el = new Element('div');
el.addClass('dg-question-label');
el.set('html', this._getCurrentQuestion().label);
document.id(this.html.el).adopt(el);
},

_addAnsweringOptions : function() {
var currentQuestion = this._getCurrentQuestion();
var options = currentQuestion.options;
var isMulti = currentQuestion.answer.length > 1;

for(var i=0;i<options.length;i++) {
var el = new Element('div');
el.addClass('dg-question-option');

var option = options[i];
var id = 'dg-quiz-option-' + this.internal.questionIndex + '-' + i;

var checkbox = new Element('input', {
name : 'dg-quiz-options',
id : id,
type : isMulti ? 'checkbox' : 'radio',
value : option
});

el.adopt(checkbox);

var label = new Element('label', { 'for' : id, 'html' : option });
el.adopt(label);

document.id(this.html.el).adopt(el);
}
},

_addAnswerButton : function() {
var el = new Element('div');
el.addClass('dg-answer-button-container');

var button = new Element('input');
button.type = 'button';
button.set('value', this.internal.labelAnswerButton);
button.addEvent('click', this._sendAnswer.bind(this));
el.adopt(button);

document.id(this.html.el).adopt(el);
},

_sendAnswer : function() {
var answer = this._getAnswersFromForm();

this.fireEvent('sendanswer', this)
var currentQuestion = this._getCurrentQuestion();
if((this.config.forceAnswer || currentQuestion.forceAnswer) && answer.length == 0) {
this.fireEvent('missinganswer', this);
return false;
}

this.user.answers[this.internal.questionIndex] = answer;

if(!this._hasAnsweredCorrectly(this.internal.questionIndex) && (this.forceCorrectAnswer || currentQuestion['forceCorrectAnswer'])){
this.fireEvent('wrongAnswer', this);
return false;
}


this.internal.questionIndex++;

if (this.internal.questionIndex == this.internal.questions.length) {
this._clearEl();
this.fireEvent('finish');
}
else {
this._displayQuestion();
}
},

_getAnswersFromForm : function() {
var ret = [];
var els = document.id(this.html.el).getElements('input');
for(var i=0;i<els.length;i++) {
if(els[i].checked) {
ret.push( {
index : i,
answer : els[i].value

});
}
}
return ret;
},

_clearEl : function () {
document.id(this.html.el).set('html','');
},

_getCurrentQuestion : function() {
return this.internal.questions[this.internal.questionIndex];
},

start : function() {
this._displayQuestion();

},

getScore : function() {
var ret = {
numCorrectAnswers : 0,
numQuestions : this.internal.questions.length,
percentageCorrectAnswers : 0,
incorrectAnswers : []
};

var numCorrectAnswers = 0;
for(var i=0;i<this.internal.questions.length; i++) {
if(this._hasAnsweredCorrectly(i)) {
numCorrectAnswers++;
}else{
ret.incorrectAnswers.push({
questionNumber : i+1,
label : this.internal.questions[i].label,
correctAnswer : this._getTextualCorrectAnswer(i),
userAnswer : this._getTextualUserAnswer(i)
})
}
}

ret.numCorrectAnswers = numCorrectAnswers;
ret.percentageCorrectAnswers = Math.round(numCorrectAnswers / this.internal.questions.length *100);

return ret;
},
_getTextualCorrectAnswer : function(questionIndex) {
var ret = [];
var question = this.internal.questions[questionIndex];
for(var i=0;i<question.answer.length;i++) {
var answer = question.answer[i];
if(question.options.indexOf(answer) == -1) {
answer = question.options[answer];
}
ret.push(answer);
}
return ret.join(', ');
},

_getTextualUserAnswer : function(questionIndex) {
var ret = [];
var userAnswer = this.user.answers[questionIndex];
for(var i=0;i<userAnswer.length;i++) {
ret.push(userAnswer[i].answer);
}
return ret.join(', ');
},
_hasAnsweredCorrectly : function(questionIndex) {
var correctAnswer = this.internal.questions[questionIndex].answer;
var answer = this.user.answers[questionIndex];

if(answer.length == correctAnswer.length ) {
for(var i=0;i<answer.length;i++) {
if(correctAnswer.indexOf(answer[i].answer) == -1 && correctAnswer.indexOf(answer[i].index) == -1){
return false;
}
}
return true;
}

return false;
}
});
rajesh at 11:27PM, 2016/03/04.
Daniel
Score: 1 of 6
Incorrect answers:
1: What is the capital of Norway ?
Correct answer : Oslo
Your answer : Stockholm
2: Who was the champion of this years soccer world cup in South Africa ?
Correct answer : Spain
Your answer : Netherlands
3: Who was the prime minister(s) of England during World War II ?
Correct answer : Sir Winston Churchill, Neville Chamberlain
Your answer : Sir Anthony Eden
4: United States has how many states
Correct answer : 50
Your answer : 51
6: In which year did Atlanta(US) arrange the summer olympics ?
Correct answer : 1996
Your answer : 2000
Configuration
Include javascript files
First of all, you'll need to include the two javascript files mootools-1.2.4-core-yc.js and dg-quiz-maker.js

Example:

<script src="/scripts/quiz-maker/js/external/mootools-1.2.4-core-yc.js"></script>
<script src="/scripts/quiz-maker/js/dg-quiz-maker.js"></script>

Configure the DG.QuizMaker object
The code below shows you an example on how to configure the quiz maker

var questions = [
{
label : 'What is the capital of Norway ?',
options : ['Stockholm', 'Oslo', 'Copenhagen'],
answer : ['Oslo']
forceAnswer : true
},
{
label : 'World champion, WC South Africa 2010 ?',
options : ['Brazil', 'Netherlands', 'Spain'],
answer : ['Spain']
},
{
label : 'Prime minister(s) of England during World War II ?',
options : ['Clement Attlee', 'Sir Winston Churchill', 'Neville Chamberlain', 'Sir Anthony Eden'],
answer : [1,2] // refers to the second and third option
}
,
{
label : 'United States has how many states',
options : ['49','50','51'],
answer : ['50']
},
{
label : 'A crocodile is a member of which family ?',
options : ['amphibian','reptile', 'vermin'],
answer : ['reptile']
},
{
label: 'In which year did Atlanta(US) arrange the summer olympics ?',
options : ['1992','1996','2000'],
answer :['1996']
}
]

function showAnswerAlert() {
$('error').set('html', 'You have to answer before you continue to the next question');
}
function clearErrorBox() {
$('error').set('html','');
}

var quizMaker = new DG.QuizMaker({
questions : questions,
el : 'questions',
listeners : {
'finish' : showScore,
'missinganswer' : showAnswerAlert,
'sendanswer' : clearErrorBox
}
});

The question object
I have created a "questions" array. Each element in the array represents a question.

label representes the label for this question
options represents the different available answering options
answer represents the correct answers. Answers can be either a text equal to the correct option, or the index of the correct answer, example in the code above: prime minister of england. Correct answers are the second and third option, i.e. index 1 and 2
forceAnswer can be used to force an answer on a specific question. forceAnswer can also be added directly to the constructor if you want to force an answer to all questions
forceCorrectAnswer can be used to force a correct answer on a specific question. forceCorrectAnswer can also be added directly to the constructor if you want to force correct answers to all questions
Constructor parameters
The constructor accepts the following parameters:

questions: A reference to the question array.
el: The element on your html page(example a <div>) where the questions will be displayed
listeners: List of functions to call when specific events occurs. See list below for valid events
Events
The script implements these events:

finished: Fires when the quiz is finished. Example: in the code above, I have specified that a function called "showScore" should be called when the quiz is finished
sendanswer: Fires when the user clicks the answer button.
missinganswer: Fires when the user clicks the answer button and answer is missing.
wrongAnswer: Fires when config option forceCorrectAnswer is set to true and wrong answer has been sent.
Public methods
There is one very important method in this script, and that is the getScore() method.

This method should be called after the user has finished the quiz. It will return an object like this:

{
numCorrectAnswers : 4
numQuestions : 6
percentageCorrectAnswers : 67
incorrectAnswers : [
{
questionNumber : 1
label : What is the capital of Norway
correctAnswer : Oslo
userAnswer : Copenhagen
},
{
questionNumber : 3
label : Prime minister of england during WWII
correctAnswer : Churchill, Chamberlain
userAnswer : Churchill, Eden
}
]
}

You can use this object to show your custom user response for the quiz. Take a look at the demo for an example of how this has been implemented

Comments
1
2
3
4
5
Paradigm Productions Great script! Any way to have multiples questions on a single page? Thanks!
PARADIGM PRODUCTIONS AT 10:30AM, 2011/02/28.
1
2
3
4
5
RBeezy doesn't appear to be working in IE7
RBEEZY AT 08:30AM, 2011/03/30.
Admin comment
1
2
3
4
5
DHTMLGoodies Thanks Rbezy,

This is actually a well known problem with IE6 and IE7 when you create radio buttons dynamically and give them a name afterwards.

I have fixed it and uploaded the download zip file.

Thanks again.
DHTMLGOODIES AT 09:15AM, 2011/03/30.
1
2
3
4
5
Samuel Vargian Great script! that what I was looking for long time

Thanks!
SAMUEL VARGIAN AT 01:23AM, 2011/08/19.
1
2
3
4
5
workerBee Hey great script , works a treat. I was wondering what would be the best/simplest way to implement another field, that can elaborate the answers better to the user, so when showscore fires it is displayed along with the correct answer. any insight would be great!. Thanks!.
WORKERBEE AT 03:11PM, 2011/09/07.
1
2
3
4
5
Tom Edwards JavaScript Quiz Maker software that you have for download is impossible use, the information and JavaScript is all over the page on notepad and not organized so that I can use it.

Can you help me get a better organized copy of JavaScript Quiz Maker to download?

Please send reply!
Tom Edwards
TOM EDWARDS AT 02:30PM, 2011/12/25.
1
2
3
4
5
Andi can I make a question that users can fill the answer by their own text?
ANDI AT 07:27AM, 2012/04/23.
1
2
3
4
5
Subhash Hi,
Thanks for the script. Is there any way you can create a MS access DB where all questions ,answers and employee details get stored.and also if you can disable the view source and back option.
SUBHASH AT 12:16PM, 2012/04/25.
1
2
3
4
5
Ted Just a dumb question--
Could a savvy user with Firebug or Chrome do "inspect element" on this quiz and see the correct answers in the javascript?
thanks-
T
TED AT 02:24PM, 2012/05/04.
1
2
3
4
5
Albert Hello,

I need some urgent help. The script doesn't seem to work in IE 9, it only shows the first question (without any possible answers). You can easily see that if you access this same page with IE 9, the demo has this same problem. Is there any way to fix this? Thank so much in advance!
ALBERT AT 10:11AM, 2012/05/14.
1
2
3
4
5
sean very nice thank you very much!
SEAN AT 05:30PM, 2012/07/14.
1
2
3
4
5
sean Is there anyway to have a hyperlink after the end of the quiz?
SEAN AT 01:35PM, 2012/07/15.
1
2
3
4
5
Michael Victoriano Hi,
Is there a way to put different images to some pages (if needed) to supplement the questionaires?
MICHAEL VICTORIANO AT 08:30AM, 2012/07/30.
1
2
3
4
5
Allan<a href="#comment1965">Michael Victoriano wrote:</a>
Hi,
Is there a way to put different images to some pages (if needed) to supplement the questionaires?

Im looking the same thing have you had any luck?
ALLAN AT 02:42AM, 2012/08/07.
1
2
3
4
5
zoli script not work in IE 9
ZOLI AT 09:25AM, 2012/08/23.
1
2
3
4
5
David Horan This is a fantastic code - the quiz is really useful.
I was wondering how one can change to font-size of the finished quiz.
Many thanks in advance,
David
DAVID HORAN AT 05:23PM, 2012/11/09.
1
2
3
4
5
Ross Is there any way to force the user to enter the correct answer before moving onto the next question? Also any news on this working in IE9?
ROSS AT 05:38AM, 2012/11/13.
Admin comment
1
2
3
4
5
DHTMLGoodies David,

The final score page is rendered inside a div with class name "result". So you can modify the fonts with css. Example:

<style type="text/css">
.score{
color:blue;
font-weight:bold;
font-size:14px;
}
</style>

Ross,

The IE9 problem has been fixed by updating to newest Mootols library.

I have implemented a new option "forceCorrectAnswer" which will give you the feature you requested. Example:

var quizMaker = new DG.QuizMaker({
questions : questions,
el : 'questions',
forceCorrectAnswer:true,
listeners : {
'finish' : showScore,
'missinganswer' : showAnswerAlert,
'sendanswer' : clearErrorBox,
'wrongAnswer' : showWrongAnswer
}
});

when forceCorrectAnswer is set to true, you will not be able to move to next question until you have answered correctly on the current one. A "wrongAnswer" event will be fired.

As you can see in the code above, I have added a listener to the "wrongAnswer" event. It will call the function showWrongAnswer which looks like this:

function showWrongAnswer(){
document.id('error').set('html', 'Wrong answer, Please try again');
}

DHTMLGOODIES AT 04:37AM, 2012/11/14.
1
2
3
4
5
RocketSMS A couple of hints ...

In files for download there is a link to dg-count-down.js that is not provided and not needed in quiz-maker.html

Also there are other classes of interest which are needed for formatting:

dg-question-option
dg-answer-button-container

I added for my own use dg-score, dg-score-span, and dg-summary-label
ROCKETSMS AT 05:37PM, 2013/01/06.
1
2
3
4
5
mloganathan dear friend, your quiz maker script which is really useful. one more thing, how to add random method 6 0ut of 10 question.
MLOGANATHAN AT 09:56PM, 2013/01/07.
1
2
3
4
5
mloganathan dear friend, your quiz maker script which is really useful. one more thing, how to add random method 6 0ut of 10 question.
MLOGANATHAN AT 09:24AM, 2013/01/14.
1
2
3
4
5
DveD Great code, but... It seems that ShowAnswerAlert doesn't work properly. It works only with a first question, missing answer in the others is ignored without alert. Thanks for your reply...DveD
DVED AT 07:51AM, 2013/03/11.
1
2
3
4
5
DveD Sorry, I found it...

DVED AT 11:32AM, 2013/03/11.
1
2
3
4
5
steve Thank you for this code, but I cannot get it to work. On the designer-developer scale, I am clearly on the designer end of the spectrum, albeit moving toward the developer end.

I copied the JS code above, put it in the head of the HTML code, downloaded the files and located them appropriately, but . . . Nothing.

I am sure it is something simple. Can you help me. Thank you!
STEVE AT 01:07AM, 2013/03/17.
1
2
3
4
5
Adeyinka Ogunkoya Hi, how can i capture the final score and store in a database.

I captured the result div in a string : $str="<div id=\"result\"></div>";
But it doesn't store the result.

Please help
ADEYINKA OGUNKOYA AT 10:33AM, 2013/04/06.
1
2
3
4
5
Javier Granda
Really useful script. Thanks!. I really want to be able to add images to some of the questions. Does anybody know how to accomplish this?? I would be very grateful

Thank you!
JAVIER GRANDA AT 09:11AM, 2013/09/03.
1
2
3
4
5
Javier Granda<a href="#comment2001">Allan wrote:</a>
<a href="#comment1965">Michael Victoriano wrote:</a>
Hi,
Is there a way to put different images to some pages (if needed) to supplement the questionaires?

Im looking the same thing have you had any luck?

I solved it:

You have to add this function on the dg-quiz-maker.js file:

_addImageElement : function() {
var elimg = new Element('img');
elimg.addClass('dg-question-image');
elimg.id='imagen';
elimg.src=this._getCurrentQuestion().image;
elimg.set('html');
document.body.appendChild(elimg);

},

Later you have to edit this function to clear every image on every question:

_sendAnswer : function() {

var answer = this._getAnswersFromForm();

this.fireEvent('sendanswer', this)
var currentQuestion = this._getCurrentQuestion();
if((this.config.forceAnswer || currentQuestion.forceAnswer) && answer.length == 0) {
this.fireEvent('missinganswer', this);
return false;
}

this.user.answers[this.internal.questionIndex] = answer;

if(!this._hasAnsweredCorrectly(this.internal.questionIndex) && (this.forceCorrectAnswer || currentQuestion['forceCorrectAnswer'])){
this.fireEvent('wrongAnswer', this);
return false;
}


this.internal.questionIndex++;

if (this.internal.questionIndex == this.internal.questions.length) {
this._clearEl();
this.fireEvent('finish');
}
else {
var q_image= document.getElementById('imagen');
q_image.destroy();
this._displayQuestion();
}
},

And finnally add it like this on the html:

label : '¿Cuál es la velocidad máxima en ciudad para un automóvil en calles?',
image: '../img/download.jpeg',
options : ['a. 40km/h.', 'b. 50km/h', 'c. 60km/h.'],
answer : ['b. 50km/h'],
forceAnswer : true
JAVIER GRANDA AT 10:35AM, 2013/09/03.
1
2
3
4
5
mickael Hello
i would like know how can i do a quiz with random question.

Thanks a lot
MICKAEL AT 02:59AM, 2013/09/05.
1
2
3
4
5
Javier Granda<a href="#comment4508">mickael wrote:</a>
Hello
i would like know how can i do a quiz with random question.

Thanks a lot

Use this function:

function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};

And then call it:

var quizMaker = new DG.QuizMaker({
questions : shuffle(questions),
el : 'questions',
forceCorrectAnswer:false,
listeners : {
'finish' : showScore,
'missinganswer' : showAnswerAlert,
'sendanswer' : clearErrorBox,
'wrongAnswer' : showWrongAnswer
}
});
JAVIER GRANDA AT 11:39AM, 2013/09/06.
1
2
3
4
5
Javier Granda<a href="#comment4508">mickael wrote:</a>
Hello
i would like know how can i do a quiz with random question.

Thanks a lot

Use this function:

function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};

And then call it:

var quizMaker = new DG.QuizMaker({
questions : shuffle(questions),
el : 'questions',
forceCorrectAnswer:false,
listeners : {
'finish' : showScore,
'missinganswer' : showAnswerAlert,
'sendanswer' : clearErrorBox,
'wrongAnswer' : showWrongAnswer
}
});
JAVIER GRANDA AT 11:40AM, 2013/09/06.
1
2
3
4
5
Poras Great script! Any way to have multiples questions on a single page? Thanks!
PORAS AT 08:05AM, 2013/09/15.
1
2
3
4
5
Peder Wessel<a href="#comment4507">Javier Granda wrote:</a>
<a href="#comment2001">Allan wrote:</a>
<a href="#comment1965">Michael Victoriano wrote:</a>
Hi,
Is there a way to put different images to some pages (if needed) to supplement the questionaires?

Im looking the same thing have you had any luck?

I solved it:

You have to add this function on the dg-quiz-maker.js file:

_addImageElement : function() {
var elimg = new Element('img');
elimg.addClass('dg-question-image');
elimg.id='imagen';
elimg.src=this._getCurrentQuestion().image;
elimg.set('html');
document.body.appendChild(elimg);

},

Later you have to edit this function to clear every image on every question:

_sendAnswer : function() {

var answer = this._getAnswersFromForm();

this.fireEvent('sendanswer', this)
var currentQuestion = this._getCurrentQuestion();
if((this.config.forceAnswer || currentQuestion.forceAnswer) && answer.length == 0) {
this.fireEvent('missinganswer', this);
return false;
}

this.user.answers[this.internal.questionIndex] = answer;

if(!this._hasAnsweredCorrectly(this.internal.questionIndex) && (this.forceCorrectAnswer || currentQuestion['forceCorrectAnswer'])){
this.fireEvent('wrongAnswer', this);
return false;
}


this.internal.questionIndex++;

if (this.internal.questionIndex == this.internal.questions.length) {
this._clearEl();
this.fireEvent('finish');
}
else {
var q_image= document.getElementById('imagen');
q_image.destroy();
this._displayQuestion();
}
},

And finnally add it like this on the html:

label : '¿Cuál es la velocidad máxima en ciudad para un automóvil en calles?',
image: '../img/download.jpeg',
options : ['a. 40km/h.', 'b. 50km/h', 'c. 60km/h.'],
answer : ['b. 50km/h'],
forceAnswer : true


Javier - I like your code. But I am struggling to get it to work to add a picture. The question is appearing, but not the picture?

I have a test picture called "test.jpg" which is in the same folder as my HTML file. I inserted the code in the JS file as you suggested and have the following code in the HTML:

var questions = [
{
label : 'Test question?',
image: 'test.jpg',
options : ['2%', '4%', '6%'],
answer : ['4%'],
forceAnswer : true
},

Would appreciate your support! Thanks!
PEDER WESSEL AT 11:20AM, 2013/10/20.
1
2
3
4
5
Sri please correct the code am getting error while displaying score
<code>
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" lang="en">
<head>
<meta http-equiv="default-style" content="text/html; charset=utf-8"/>
<title>LNS</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

$(function() {


$(".ans").click(function(e){
var res = $(this).attr("data-type")
var clickCounter = $("#count").data("clickCounter");
clickCounter = (clickCounter + res);
$("#count").data("clickCounter", res);
$("#count").html(clickCounter);
});

$("#answer1_q1").click(function() {
$("#answers_q1").html('Correct');
});
$("#answer2_q1").click(function() {
$("#answers_q1").html('Wrong');
});

$("#answer1_q2").click(function() {
$("#answers_q2").html('Correct');
});
$("#answer2_q2").click(function() {
$("#answers_q2").html('Wrong');
});

$("#answer1_q3").click(function() {
$("#answers_q3").html('Correct');
});
$("#answer2_q3").click(function() {
$("#answers_q3").html('Wrong');
});
/**/

});
</script>
</head>
<body>
<style type="text/css">
.hide{
display:none;
}
</style>

<div id="Question1">Question 1
<div id="answers_q1">
<div id="answer1_q1" class="ans" data-type="1">answer 1</div>
<div id="answer2_q1" class="ans" data-type="0">answer 2</div>
</div>
</div>
<br />
<div id="Question2">Question 2
<div id="answers_q2">
<div id="answer1_q2" class="ans" data-type="1">answer 1</div>
<div id="answer2_q2" class="ans" data-type="0">answer 2</div>
</div>
</div>
<br />
<div id="Question3">Question 3
<div id="answers_q3">
<div id="answer1_q3" class="ans" data-type="1">answer 1</div>
<div id="answer2_q3" class="ans" data-type="0">answer 2</div>
</div>
</div>
<br />
<div id="total">Total Results
<div id="answers_total">
You have <span id="count"></span> correct answers out of total 3 Questions!!!
</div>
</div>
</body>
</html>
SRI AT 03:29AM, 2013/11/13.
1
2
3
4
5
Satender Sharma Thanks! Great work.
I want to add a timer and question pallet (where question numbers are mentioned, so user can switch to any question during exam). Any help would be appreciable.


SATENDER SHARMA AT 08:09AM, 2014/01/24.
1
2
3
4
5
Will_C Is there any way the entire page could reload at the user input of next? Basically I am looking for a one question per page script like this but when the user selects next it reloads the entire page.
WILL_C AT 06:22PM, 2014/04/21.
1
2
3
4
5
Brian Love the code. But I can get the image code above working. Any help or a link to a working model would be HUGELY appreciated!
BRIAN AT 03:07PM, 2014/07/22.
1
2
3
4
5
sam Is posible send email results?
SAM AT 01:13PM, 2014/07/31.
1
2
3
4
5
ryan how to edit the submit button..css cant do it .dg-answer-button-container
RYAN AT 11:09AM, 2014/08/18.
1
2
3
4
5
dadz Great code!thanks, btw how to set a timer?
DADZ AT 02:10AM, 2014/08/27.
1
2
3
4
5
meraj Great Work!!!Thanks a lot...

<p>Is there any way to move directly between questions...say i want to move to question 3 directly from question 1 and so on
MERAJ AT 11:47PM, 2014/10/13.
1
2
3
4
5
SCOTTR Love the script, using the randomizer function posted above with it. I'm curious if there is a way to make this script randomly pull a pre-defined number of questions thou? Like say I have 250 questions loaded and I want it to randomly select 150 of those to populate the exam with?

Many thanks!
SCOTTR AT 09:20AM, 2015/01/07.
1
2
3
4
5
Joram Kimata Hello!

Nice script but i wonder on how to create questions and save them to the database any soln i will appreciate
JORAM KIMATA AT 10:49AM, 2015/04/01.
1
2
3
4
5
Serge Hello guys

I am trying to do the quiz. Is it possible to create a file after finishing the quiz and put there following information, like:

1) question 1
What is the capital of Great Britain
> London - CORRECT

2) question 2
What is the capital of France
> Lyon - INCORRECT

etc.
thank you in advance.
SERGE AT 09:20AM, 2015/06/16.
1
2
3
4
5
Max Demars Is it possible to have version without mootools? Just pure AMD library.
MAX DEMARS AT 07:17AM, 2015/10/02.
1
2
3
4
5
Max Demars Am I wrong? It seems that you use mootools only to extend the Class object? If yes, it would be easy to exclude mootols dependancy.
MAX DEMARS AT 07:21AM, 2015/10/02.
1
2
3
4
5
saidihasan how to add images, in this script ?
SAIDIHASAN AT 03:33AM, 2016/01/15.
1
2
3
4
5
nen gawker Awesome script. Thank you.

How many questions it can load? Because right now I can only add up to 8..is javascript var has limits? please advise..
NEN GAWKER AT 04:04PM, 2016/02/03.
1
2
3
4
5
rajesh how to add count time .js
<script type="text/javascript" src="js/dg-count-down.js"></script>
RAJESH AT 01:43AM, 2016/02/19.
1
2
3
4
5
rajesh Adding Image code is right process? its not working..
if(!window.DG) {
window.DG = {};
};

DG.QuizMaker = new Class( {
Extends : Events,

validEvents : ['start','sendanswer', 'correctanswer','wronganswer', 'finish','missinganswer','wrongAnswer'],

config: {
seconds: null,
forceAnswer : false
},

html : {
el : null
},

internal : {
questionIndex : 0,
questions : null,
labelAnswerButton : 'Answer'
},

user : {
answers : []
},

forceCorrectAnswer:false,

initialize : function(config) {
if(config.el) {
this.html.el = config.el;
}
if(config.forceAnswer) {
this.config.forceAnswer = config.forceAnswer;
}
if(config.forceCorrectAnswer !== undefined)this.forceCorrectAnswer = config.forceCorrectAnswer;
if(config.labelAnswerButton) {
this.internal.labelAnswerButton = config.labelAnswerButton;
}

this.internal.questions = config.questions;

if(config.listeners) {
for(var listener in config.listeners) {
if(this.validEvents.indexOf(listener)>=0) {
this.addEvent(listener, config.listeners[listener]);
}
}
}
},

_displayQuestion : function() {
this._clearEl();
this._addQuestionElement();
this._addAnsweringOptions();
this._addAnswerButton();
},

_addQuestionElement : function() {
var el = new Element('div');
el.addClass('dg-question-label');
el.set('html', this._getCurrentQuestion().label);
document.id(this.html.el).adopt(el);
},

_addAnsweringOptions : function() {
var currentQuestion = this._getCurrentQuestion();
var options = currentQuestion.options;
var isMulti = currentQuestion.answer.length > 1;

for(var i=0;i<options.length;i++) {
var el = new Element('div');
el.addClass('dg-question-option');

var option = options[i];
var id = 'dg-quiz-option-' + this.internal.questionIndex + '-' + i;

var checkbox = new Element('input', {
name : 'dg-quiz-options',
id : id,
type : isMulti ? 'checkbox' : 'radio',
value : option
});

el.adopt(checkbox);

var label = new Element('label', { 'for' : id, 'html' : option });
el.adopt(label);

document.id(this.html.el).adopt(el);
}
},

_addAnswerButton : function() {
var el = new Element('div');
el.addClass('dg-answer-button-container');

var button = new Element('input');
button.type = 'button';
button.set('value', this.internal.labelAnswerButton);
button.addEvent('click', this._sendAnswer.bind(this));
el.adopt(button);

document.id(this.html.el).adopt(el);
},

_sendAnswer : function() {
var answer = this._getAnswersFromForm();

this.fireEvent('sendanswer', this)
var currentQuestion = this._getCurrentQuestion();
if((this.config.forceAnswer || currentQuestion.forceAnswer) && answer.length == 0) {
this.fireEvent('missinganswer', this);
return false;
}

this.user.answers[this.internal.questionIndex] = answer;

if(!this._hasAnsweredCorrectly(this.internal.questionIndex) && (this.forceCorrectAnswer || currentQuestion['forceCorrectAnswer'])){
this.fireEvent('wrongAnswer', this);
return false;
}


this.internal.questionIndex++;

if (this.internal.questionIndex == this.internal.questions.length) {
this._clearEl();
this.fireEvent('finish');
}
else {
this._displayQuestion();
}
},

_getAnswersFromForm : function() {
var ret = [];
var els = document.id(this.html.el).getElements('input');
for(var i=0;i<els.length;i++) {
if(els[i].checked) {
ret.push( {
index : i,
answer : els[i].value

});
}
}
return ret;
},

_clearEl : function () {
document.id(this.html.el).set('html','');
},

_getCurrentQuestion : function() {
return this.internal.questions[this.internal.questionIndex];
},

start : function() {
this._displayQuestion();

},

getScore : function() {
var ret = {
numCorrectAnswers : 0,
numQuestions : this.internal.questions.length,
percentageCorrectAnswers : 0,
incorrectAnswers : []
};

var numCorrectAnswers = 0;
for(var i=0;i<this.internal.questions.length; i++) {
if(this._hasAnsweredCorrectly(i)) {
numCorrectAnswers++;
}else{
ret.incorrectAnswers.push({
questionNumber : i+1,
label : this.internal.questions[i].label,
correctAnswer : this._getTextualCorrectAnswer(i),
userAnswer : this._getTextualUserAnswer(i)
})
}
}

ret.numCorrectAnswers = numCorrectAnswers;
ret.percentageCorrectAnswers = Math.round(numCorrectAnswers / this.internal.questions.length *100);

return ret;
},
_getTextualCorrectAnswer : function(questionIndex) {
var ret = [];
var question = this.internal.questions[questionIndex];
for(var i=0;i<question.answer.length;i++) {
var answer = question.answer[i];
if(question.options.indexOf(answer) == -1) {
answer = question.options[answer];
}
ret.push(answer);
}
return ret.join(', ');
},

_getTextualUserAnswer : function(questionIndex) {
var ret = [];
var userAnswer = this.user.answers[questionIndex];
for(var i=0;i<userAnswer.length;i++) {
ret.push(userAnswer[i].answer);
}
return ret.join(', ');
},
_hasAnsweredCorrectly : function(questionIndex) {
var correctAnswer = this.internal.questions[questionIndex].answer;
var answer = this.user.answers[questionIndex];

if(answer.length == correctAnswer.length ) {
for(var i=0;i<answer.length;i++) {
if(correctAnswer.indexOf(answer[i].answer) == -1 && correctAnswer.indexOf(answer[i].index) == -1){
return false;
}
}
return true;
}

return false;
}
});
RAJESH AT 11:27PM, 2016/03/04.
Post your comment
Your name:
Your email:
Don't have an avatar? Create one at Gravatar.com.


Confirmation code:

Submit

Go to cbolson.com


About/Contact | A good idea? | Submit a script | Privacy notice
© 2005 - 2016 dhtmlgoodies.com
Daniel at 12:04PM, 2016/05/04.

Post your comment

Don't have an avatar? Create one at Gravatar.com.

Confirmation code:

Go to cbolson.com


About/Contact | A good idea? | Submit a script | Privacy notice
© 2005 - 2017 dhtmlgoodies.com