Click here to Skip to main content
12,819,538 members (33,118 online)
Click here to Skip to main content
Add your own
alternative version


17 bookmarked
Posted 16 Oct 2006

Object Oriented JavaScript quiz

, 11 Nov 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
Object oriented JavaScript quiz which can easily be customized to add more features.


This is basically a log of a dynamic JavaScript quiz I created. It makes extensive use of JavaScript's object oriented features. Anyone interested in doing really advanced stuff in JavaScript can learn a lot from the methods used in this application. Doing this from scratch took me approximately two days.

What does this application do? It allows someone to add as many modules containing as many questions with as many choices as you like. All this is done without editing core files. It is also possible to replace the questions.js with AJAX calls....

What type of quiz is this? This is a multiple choice quiz.

File structure:

  • index.html - the file loaded into the browser which will display the quiz.
  • quiz.js - JavaScript code file containing the core quiz functions.
  • test.js - JavaScript code file containing the core interface functions.
  • quiz.css - Cascading styleheets file containing the directives that control the visual elements of the quiz, like font and color.
  • questions.js - JavaScript code file where the questions can be added with a specific syntax.


I know it does not look like much, but believe it or not, this is what brings it all together:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="quiz.js"></script>
<script type="text/javascript" src="questions.js"></script>
<script type="text/javascript" src="test.js"></script>
<link rel="stylesheet" href="quiz.css" />
<body onLoad="displayset(0,0)">
<form name="submitquestions" action="index.html" method="get">
<div id="headdiv" class="layout">
<div id="modulediv" class="layout" >
<table align="center"><tr>
totalmodules =
for(i = 0;i < totalmodules;i++)
    currentmodule = quiz1.get(i)
    document.writeln('<td class="module" cellspacing=0>')    
    totalsets =
        currentset = currentmodule.get(x)
        document.writeln('<a href="javascript:displayset('+ i +','+ x +')">'+ 
    +'(' + + ')</a>|<br>')
<div id="sectionheader" class="layout">
<h3 id="hl"> </h3>
<div id="bodydiv" class="layout">
<div id="footer" class="layout">
<input type="button" onclick="displayresults()" value="Submit" />


You can call this file the brain of the application. This is where the object classes used all over the application are defined.

/* *************************************************************************
Purpose of utility functions are to allow 
a novice user to add questions to questions.js
without having to worry about naming objects
var globalmodule
var globalset
var globalquiz //really not necessary but put for completeness
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function nextmodule(name)
function nextset(name)
function addproblem(question,answer)
/* ***********************************************************************
function quiz(name)
    this.right = 0
    this.wrong = 0 = name
    this.modules = new Array()
quiz.prototype.add = function(name)
    this.modules.push(new module(name)) 
    globalmodule = this.modules[this.modules.length-1]
quiz.prototype.get = function(module)
    return this.modules[module] 
} = function()
    return this.modules.length 

/* *********************************************************************
function module(name)
{ = name
    this.sets = new Array()
module.prototype.add = function(name)
    this.sets.push(new set(name))
    globalset = this.sets[this.sets.length-1]
module.prototype.get = function(set)
    return this.sets[set] 
} = function()
    return this.sets.length 
function set(name)
{ = name
    this.rightanswers = 0
    this.problems = new Array()
set.prototype.add = function(args)
    this.problems.push(new problem(args)) 
set.prototype.get = function(problem)
    return this.problems[problem] 
} = function()
    return this.problems.length 
function problem(args)
    this.choices = new Array() 
    this.selection = -1 //have not chosen an answer
    this.question = args[0]
    this.answer = chars.indexOf(args[1])
    for (var i = 2; i < args.length; i++) 
problem.prototype.totalchoices = function()
    return this.choices.length 
problem.prototype.getchoice = function(choice)
    return this.choices[choice] 


This file contains the code that dynamically renders the quiz using the routines from quiz.js based on the content of questions.js, which I will show next.

/********************************************** JavaScript Document
Interface functions responsible for displaying 
quiz elements and general flow of quiz
function displayset(module,set)
    getmodule = quiz1.get(module)
    getset = getmodule.get(set)
    globalset = getset

    //set subheader for set
    var sheader = document.getElementById('hl')
    headertext = + " - " + + 
                 ": Answer the following questions"
    sheader.childNodes[0].nodeValue = headertext

    // clear questions
    questionsdiv = document.getElementById('bodydiv')
        for(var i = 0;i<questionsdiv.childNodes.length;i++)
    //write out questions and choices for current selected set
    totalproblems =
    questionlist = document.createElement('OL')

    for(var i=0;i<totalproblems;i++)
        currentproblem = getset.get(i)
        listitem = document.createElement('LI')
        questionbreak = document.createElement('BR')
        listquestion = document.createTextNode(currentproblem.question)

        //list choices for current problem
        choicelist = document.createElement('UL')

        uniqueid = uniquename(5)
        totalchoices = currentproblem.totalchoices()
        for(var x = 0;x < totalchoices;x++)
            choiceitem = document.createElement('LI') 
            listradio = document.createElement('INPUT')

            choiceitemchar = document.createTextNode(chars.charAt(x) + ". ")
            choiceitemtext = 
function selectoption(module,set,problem,roption)
    //alert(module +"/"+ set +"/"+ problem +"/"+ roption)
    getmodule = quiz1.get(module)
    getset = getmodule.get(set)
    getproblem = getset.get(problem)
    getproblem.selection = roption
function uniquename(length)
    name = "";
        i = Math.floor(Math.random() * 52);
        name += chars.charAt(i);
    return name;
function displayresults()
    var noanswer = new Array()
    globalset.rightanswers = 0
    for(var i = 0;i<;i++)
        getproblem = globalset.get(i)
        if(getproblem.selection == -1)
            noanswer.push(i + 1)
        if(getproblem.selection == getproblem.answer)
        case 0 :
            percentage = Math.round(100 * 
            //totalwrong = ( - globalset.rightanswers)
            var resultstring = +' - '+ + '\n\n'
            resultstring+= 'Your Score is ' + percentage + '%'
            resultstring+= ' ('+ globalset.rightanswers+'/'+ +')\n\n'
            resultstring+= 'Question Your Answer Correct Answer Result \n'
            for(var x=0;x<;x++)
                question = x+1
                getproblem = globalset.get(x)
                resultstring+=' '+ question + ' '
                resultstring+=chars.charAt(getproblem.selection) + ' '
                resultstring+=chars.charAt(getproblem.answer) + ' '
                  (getproblem.selection == getproblem.answer)? 'o\n':'x\n'

        default :
        var noanswerstring =""
        for(var j=0;j<noanswer.length;j++)
            noanswerstring += 'Question (' + noanswer[j] + ')\n' 
        alert("The follwoing questions were not answered:\n\n" + noanswerstring)

Function created to address issue with internet explorer after experiencing 
problems dynamically setting the name attribute of radio buttons. 
N.B. Other browsers don't need this.
function iefix()
        rawdata = document.getElementById('bodydiv').innerHTML
        fixdata = rawdata.replace(/value/g,"name")
        document.getElementById('bodydiv').innerHTML = fixdata


The following are simple examples showing how questions can be added. Although currently the index.html page is hard coded for a single quiz named quiz1, it is possible to define multiple quizzes.

Follow these instructions to add new modules, sets, and questions:

  1. To add a new module, simply put in: nextmodule('Module Name'). 'Module Name' will be displayed in the module selection.
  2. To add a new set, simply put in: nextset('Set Name'). 'Set Name' will be displayed in the set selection.
  3. To add a question, observe the following pattern: addproblem("your question",position of the correct answer,"answer1","answer2","answer3" etc.).
var quiz1 = new quiz('Sample Name')
globalquiz = quiz1
nextset('set 1')
addproblem("How old are you",'a',"10 to 13 years","14 to 20 years","21 to 25 years")
addproblem("your birth month?",'c',"Jan","mar","may","jul","dec")
addproblem("How old are you",'b',"10 to 13 years","14 to 20 years","21 to 25 years")
nextset('set 2')
addproblem("How old are you",'a',"10 to 13 years","14 to 20 years","21 to 25 years")
addproblem("your birth month?",'a',"Jan","mar","may","jul","dec")
addproblem("How old are you",'b',"10 to 13 years","14 to 20 years","21 to 25 years")
addproblem("your birth month?",'d',"Jan","mar","may","jul","dec")
nextset('set 1')
addproblem("How old are you",'b',"10 to 13 years","14 to 20 years","21 to 25 years")
addproblem("your birth month?",'b',"Jan","mar","may","jul","dec")
addproblem("How old are you",'a',"10 to 13 years","14 to 20 years","21 to 25 years")
addproblem("your birth month?",'c',"Jan","mar","may","jul","dec")
nextset('set 2')
addproblem("How old are you",'c',"10 to 13 years","14 to 20 years","21 to 25 years")
addproblem("your birth month?",'b',"Jan","mar","may","jul","dec")
addproblem("How old are you",'b',"10 to 13 years","14 to 20 years","21 to 25 years")
addproblem("your birth month?",'d',"Jan","mar","may","jul","dec")


This file can be modified to change the look and feel of the quiz elements.

/* CSS Document */
div.layout { margin:0px 0px 0px 0px; }
#modulediv { text-align:center; padding:0px 0px 0px 0px; }
#headdiv { text-align:center ; }
td.module { max-width:80px;}
#bodydiv { overflow:scroll;height:350px; max-height:350px; 
           overflow-x:hidden;border:thin inset black;}
body {margin-top:0px;}
#sectionheader {padding:0px 0px 0px 10px;}
ul {list-style-type:none;}

This script can be seen in action here.

Final Comments

The idea behind this is the ability to take quiz data and:

  1. Dynamically create the interface required for a user to take the quiz.
  2. Provide information about the user's choices and send them back to be verified.

So, given the object oriented structure, it is also possible to load the quiz data from another source without changing anything. Let's say, for example, your quiz is stored in XML files. You could add your own xml_question_reader.js, then you could say the following in questions.js:

xml_test_source = load_xml_source_tree("path/to/quiz.xml")

for(x in xml_test_source.modules)
    xml_module = xml_test_source.modules[x]

    for(y in xml_module.sets)
        xml_set = xml_module.sets[y]

        for(z in xml_set.problems)
           xml_problem = xml_set.problems[z]

It is important to note that the XML source could also be generated by any server-side language. However, the script may have to be changed slightly, so you won't have to provide the correct answer in JavaScript at the time of initializing a problem.

This script demonstrates many key concepts including dynamically adding form elements to a page, and has also been tested in IE, Opera, and Firefox. Enjoy.

N.B. The previous script has no real error testing, and should be used for educational purposes only.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
Saint Lucia Saint Lucia
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionI wanted to implement this code with XML driven data Pin
Member 999149818-Apr-13 1:19
memberMember 999149818-Apr-13 1:19 
QuestionChange from radio button to checkboxes Pin
Member 820052116-Apr-12 6:19
memberMember 820052116-Apr-12 6:19 
GeneralHelp Needed Pin
joshiley78613-Jun-11 0:37
memberjoshiley78613-Jun-11 0:37 
Hello silasco

I just wonder how should I pick data from an external XML file. Any help with the code is really appreciated. The article is really well written however i tried to replaced/ populated the content of questions.js file with an external XML file containing the exactly similar data.

Please help. !!

GeneralRe: Help Needed Pin
silasco8-Jul-11 9:14
membersilasco8-Jul-11 9:14 
GeneralRe: Help Needed Pin
umakantdixit884-Dec-12 3:23
memberumakantdixit884-Dec-12 3:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170308.1 | Last Updated 11 Nov 2006
Article Copyright 2006 by silasco
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid