| home / programming / javascript / beginning / chap6 / 6 |
[previous] [next] |
|
The Trivia QuizCreating the Answer Radio ButtonsWe saw in the code above, that the radio buttons required will be inserted by the getQuestion() function, and the buttonCheckQ_onclick() function is connected to the button's onclick event handler. We'll now add these functions to the top of the page in the same script block as the answerCorrect() function that we defined in Chapter 3. Add the following lines to the top of the trivia_quiz.htm page.
We will discuss the getQuestion() function first, which is used to build up the HTML needed to display the question to the user. We first want to select a random question from our questions array, so we need to generate a random number, which will provide the index for the question. We store this number in the global variable questionNumber that we declared at the top of the script block.
We generate a random number between 0 and 1 using the Math.random() method, and then multiply that by the number of questions in the questions array. This number is converted to an integer using the Math object's floor() method, which returns the lowest integer part of a floating point number. This is exactly what we want here: a randomly selected number from 0 to questions.length - 1. Don't forget that arrays start at an index of 0. Our next task is to create the radio buttons, which allow the user to answer the question. We do this by building up the HTML that needs to be written to the page inside the variable questionHTML. |
| home / programming / javascript / beginning / chap6 / 6 |
[previous] [next] |
Created: February 15, 2001
Revised: February 15, 2001