A Radio Button Quiz

Jake Howlett, 9 January 2001

Category: JavaScript; Keywords: radio array math

This example is going be a little quiz using Radio-Buttons and JavaScript (not a quiz about radio-buttons as the title may suggest). It is not that I thought of this as a useful application, more that the techniques used are quite handy. What's more, if it were really a quiz, you could cheat buy viewing the source-code.

The principles demonstrated are that of Multi-Dimensional JavaScript Arrays and of working with Radio-Buttons in JavaScript functions.

Let's get started with the quiz:

Question 1 (Muliple Choice) What is 4 squared?

12 14 16 18

Question 2 (Muliple Choice) Which is the best browser?

Internet Explorer Netscape Navigator Opera

Question 3 (Muliple Choice) What is the best description of domino?

A pizza delivery company
A powerful, yet misused, internet application server
The effect of pushing the first of a line of bicycles over

Question 4 (Boolean) Jake is really cool ?

True False

Mark My Answers

Percentage:


So, how did you do? Before you start to mail me with complaints, a couple of the answers are just my opinion. Sorry.

So let's look at the function that is called by the "Mark Answers" link:

function getScore( form ) {

var AnswersAndObjects = new Array();
AnswersAndObjects[0] = ["16", form.question1];
AnswersAndObjects[1] = ["IE", form.question2];
AnswersAndObjects[2] = ["AS", form.question3];
AnswersAndObjects[3] = ["T", form.question4];

var theScore = 0;

for (i=0; i < AnswersAndObjects.length; i++) {
currQuestionObject = AnswersAndObjects[i][1];
for (j=0; j<currQuestionObject.length; j++){
if (currQuestionObject[j].checked && currQuestionObject[j].value == AnswersAndObjects[i][0] ) {
theScore++;
break;
}
}
}

theScore = Math.round( theScore/AnswersAndObjects.length*100 );

form.percentage.value = theScore + "%";
}


What does it do?

First thing is to build an Array that has 4 elements, one for each of the questions. In turn, each of these contain two more elements, one for the correct answer and one for the radio-group object reference.

With the array of the question's answers and objects, the function now loops through each question, getting a hold on the object, looping through all the possible answers and comparing them to the stored one. Whenever an answer is found to be correct the "score" variable is increased by one.

The last thing to do is to convert this score in to a percentage, by dividing by the number of question and multiplying by a hundred. All we need do then is to use the answer. In this case it is placed in to an input field, called "percentage".