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 05:30PM, 2011/02/28.
RBeezy
doesn't appear to be working in IE7
RBeezy at 02:30PM, 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 03:15PM, 2011/03/30.
Samuel Vargian
Great script! that what I was looking for long time

Thanks!
Samuel Vargian at 07: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 09: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 09:30PM, 2011/12/25.
Andi
can I make a question that users can fill the answer by their own text?
Andi at 01:27PM, 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 06: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 08: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 04:11PM, 2012/05/14.
sean
very nice thank you very much!
sean at 11:30PM, 2012/07/14.
sean
Is there anyway to have a hyperlink after the end of the quiz?
sean at 07: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 02:30PM, 2012/07/30.
zoli
script not work in IE 9
zoli at 03:25PM, 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 12:23AM, 2012/11/10.
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 12:38PM, 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 11: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.htmlAlso there are other classes of interest which are needed for formatting:dg-question-optiondg-answer-button-containerI added for my own use dg-score, dg-score-span, and dg-summary-label
RocketSMS at 12:37AM, 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 04:56AM, 2013/01/08.
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 04:24PM, 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 01:51PM, 2013/03/11.
DveD
Sorry, I found it...
DveD at 05:32PM, 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 07: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 04:33PM, 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 03:11PM, 2013/09/03.
mickael
Helloi would like know how can i do a quiz with random question.Thanks a lot
mickael at 08:59AM, 2013/09/05.
Poras
Great script! Any way to have multiples questions on a single page? Thanks!
Poras at 02:05PM, 2013/09/15.
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 10: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 03:09PM, 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 12:22AM, 2014/04/22.
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 09:07PM, 2014/07/22.
sam
Is posible send email results?
sam at 07:13PM, 2014/07/31.
ryan
how to edit the submit button..css cant do it .dg-answer-button-container
ryan at 05:09PM, 2014/08/18.
dadz
Great code!thanks, btw how to set a timer?
dadz at 08: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 05:47AM, 2014/10/14.
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 04:20PM, 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 04:49PM, 2015/04/01.
Serge
Hello guysI 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 1What is the capital of Great Britain> London - CORRECT2) question 2What is the capital of France> Lyon - INCORRECTetc.thank you in advance.
Serge at 03:20PM, 2015/06/16.
Max Demars
Is it possible to have version without mootools? Just pure AMD library.
Max Demars at 01:17PM, 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 01:21PM, 2015/10/02.
saidihasan
how to add images, in this script ?
saidihasan at 10: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 11:04PM, 2016/02/03.
rajesh
how to add count time .js<script type="text/javascript" src="js/dg-count-down.js"></script>
rajesh at 08: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 06:27AM, 2016/03/05.
jinosh m
what is 'cry uncle', 'think again multiple choice quizes', ' match maker matching quizes', 'linear world ordering quizzes'
jinosh m at 12:33PM, 2018/07/29.
Mohan
How to edit/format "Answer" button. Would like to change button size, color, etc.
Mohan at 05:12PM, 2018/11/08.
Mohan
To modify Answer Button, add this to your style sheet (CSS). Take care of other buttons as this code will change all default buttons. Here is the CSS code.

input[type=button] {
margin-top: 30px;
width: 150px;
color:#08233e;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
padding:10px;
background-color:rgba(255,204,0,1);
border:1px solid #ffcc00;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
border-bottom:1px solid #9f9f9f;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
cursor:pointer;
}

input[type=button]:hover {
background-color:rgba(255,204,0,0.8);
}
Mohan at 07:13PM, 2018/11/11.
Pete
Thanks for sharing this very useful quiz script. I wondered how we can add a button at the end of the results form for 'retry quiz'? Thanks again
Pete at 08:45PM, 2019/12/26.
Atish
The radio button is not displaying when I am pasting the HTML code in my blogger.....
Please advise me
Atish at 06:47PM, 2020/05/31.
Mwas
How can I fetch Quiz from json ?
Kindly help me
Mwas at 11:49AM, 2021/05/30.

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 - 2024 dhtmlgoodies.com