Introduction To Javascript
The Quiz Script

The quiz script uses a form with text boxes to make a simple quiz. The user fills in the answers and a function checks the answers. The basic script is as follows.

HTML to make the form

<form name="myForm">
What is the capital of France? <input type="text" name="quOne"><BR>
What is the capital of Spain? <input type="text" name="quTwo"><BR>
<button onclick="checkAnswers()">Check your answers</button>

Javascript in <head>

<script type="text/javascript">
var answers = new Array("Paris", "Madrid")
var userAnswers = new Array
function checkAnswers() {
userAnswers[0] = document.myForm.quOne.value
userAnswers[1] = document.myForm.quTwo.value
var count = answers.length
var correct = 0
for (var i = 0;i<count;i++) {
if(userAnswers[i]==answers[i]) {
alert("You got " + correct)

An array of answers is created in line 2. The array in line 3 is declared but no values are set. It will hold the user's answers. In the function, lines 5 and 6 look up the user's answers (the entries in the text boxes). Line 7 users accesses the array's length property, in this case 2 because there are 2 values in the area. The loop which begins in line 9 uses the value of count as the number at which to stop the loop. (The loop will count 0 then 1). In line 10 the script compares the user's answer with the true answer. If the value is correct (notice the 2 x = signs) then one is added to the value of the variable correct, declared in line 8. Lines 12 and 13 have the curly braces which close the if and the for statements. Line 14 returns the result in a message box and line 15 ends the function.

Exercise 12

The script and HTML for the quiz above needs some improving. Increase the number of questions to 10 and amend the Javascript and HTML as required. Some formatting on the HTML would improve the look of the page. You can alter the appearance of form items using stylesheets.