JavaScript : Creating a Random Quiz
Contents ]
Dr Benton

Checking the Answers

Once the drop-down lists are set, the form will operate by itself. When visitors click on the submission button, the selected answers are verified. A slight change to the form and a script are all we need:

41: <INPUT TYPE="button" VALUE="Submit" OnClick="test(this.form)">

[...]

104: function test(Reponse)
105: {
106:   SlcRsp = new Array(Reponse.Select1.selectedIndex, Reponse.Select2.selectedIndex, Reponse.Select3.selectedIndex)
107:   Score = new Number
108:   Score = 0
109:   for (var k = 0; k < 3; k++)
110:   {
111:     if (SlcRsp[k] == Repons[Quest[k]])
112:        Score = Score + 1
113:   }
114:   
115:   location = "scor_" + Score + ".htm"
116: }
117:
118: </SCRIPT>

Line 41, we define a call to the function test() to which the form is submitted.

We use a for loop (line 109) to check the accuracy of each of the three answers supplied. Beforehand we store the list of the user-selected answers in an array named slcRsp. To do this, we simply read the property selectedIndex of each list. In line 111, we compare the selected answers one by one with the correct answers, the numbers of which are kept in the array Repons.

Once the outcome of the test has been established, the browser fetches the page corresponding to the visitor's score. For two correct answers, the page scor_2.htm is displayed. Now it is your turn to create these pages...

With your newly acquired know-how -you can now go ahead and design an entertaining little quiz! How about another round?




  1   2   3   4   5   6