JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

The Trivia Quiz—Storing the Questions Using Arrays

OK, it's time to make our first steps in building the online trivia quiz. We're going to lay the foundations by defining the data that makes up the questions and answers used in the quiz.

In this chapter, we're just going to define multiple-choice-based questions, which have a single letter answer. We'll be using arrays to store the questions and answers: a two-dimensional array for the questions and a single-dimensional one for the matching answers.

The format of each multiple-choice question will be the question followed by each of the possible choices for answers. The correct answer to the question is specified using the letter corresponding to that answer.

For example, the question, "Who were The Beatles?" has three options:

  1. A sixties rock group from Liverpool

  2. Four musically gifted insects

  3. I don't know. Can I have the questions on Baseball please?

And the answer in this case is A.

So how do we store this information in our arrays? Let's look at the array holding the questions first. We will define the array something like this:

Index

0

1

2

0

Text for Question 0

Text for Question 1

Text for Question 2

1

Possible Answer A for Question 0

Possible Answer A for Question 1

Possible Answer A for Question 2

2

Possible Answer B for Question 0

Possible Answer B for Question 1

Possible Answer B for Question 2

3

Possible Answer C for Question 0

Possible Answer C for Question 1

Possible Answer C for Question 2

Of course we can extend this array if we create further questions or have more than three possible answers for a question.

The answers array will then be defined something like this:

Index

Value

0

Correct answer to Question 0

1

Correct answer to Question 1

2

Correct answer to Question 2

Again, we can extend this array as we add more questions.

Now that we have an idea of how we are going to store the question data, let's have a look at the code. The name of the page to add the code to is trivia_quiz.htm. We start by creating the HTML tags at the top of the page.

<html>
<head>
<title>Wrox Online Trivia Quiz</title>
</head>
<body>

Then, in the body of the page, we start a JavaScript block, in which we declare two variables, questions and answers, and define them as new arrays. The purpose of these variables should be pretty self-explanatory! However, as in the rest of the code, we add comments so that it is easy to work out what we are doing.

<script language="JavaScript" type="text/javascript">
    
// questions and answers arrays will holds questions and answers
var questions = new Array();
var answers = new Array();

Next we move straight on to define our first question. Since the questions will be in a two-dimensional array, our first task is to set questions[0] to a new array. We assign the first element in this array, questions[0][0], to the text of the question, and the following elements to the possible answers.

// define question 1
questions[0] = new Array();
    
// the question
questions[0][0] = "The Beatles were";
    
// first choice
questions[0][1] = "A sixties rock group from Liverpool";
    
// second choice
questions[0][2] = "Four musically gifted insects";
    
// third choice
questions[0][3] = "I don't know. Can I have the questions on Baseball please?";

Having defined the first question, let's set the first answer. For multiple-choice questions we just need to set the element with the corresponding index in the answers array to the character representing the correct choice. In the previous question the correct answer is "A sixties rock group from Liverpool". As this is the first choice, its letter is A.

// assign answer for question 1
answers[0] = "A";

Let's define two more questions for the quiz. They both take the same format as the first question, though they differ in having four options for the user to choose from. In the next chapter, you'll see that our code can handle this, and indeed we can have as many options as we like.

// define question 2
questions[1] = new Array();
questions[1][0] = "Homer Simpson's favorite food is";
questions[1][1] = "Fresh salad";
questions[1][2] = "Doughnuts";
questions[1][3] = "Bread and water";
questions[1][4] = "Apples";
    
// assign answer for question 2
answers[1] = "B";
    
// define question 3
questions[2] = new Array();
questions[2][0] = "Lisa Simpson plays which musical instrument?";
questions[2][1] = "Clarinet";
questions[2][2] = "Oboe";
questions[2][3] = "Saxophone";
questions[2][4] = "Tubular bells";
    
// assign answer for question 3
answers[2] = "C";

We end the script block by creating an alert box that tells us that the array has been initialized.

alert("Array Initialized");
    
</script>
</body>
</html>

Набор бесплатных поисковых инструментов
Сегодня интернет стал хорошим источником прибыли как для создателей сайтов так и для бизнеса. Многие создают или заказывают интернет ресурсы чтобы подзаработать в сети. Если у вашего ресурса замечательный дизайн и в нем много полезной информацией для людей, он может быть практически невидим поисковыми машинами в следствие чего иметь небольшую посещаемость. Чтобы изменить эту ситуацию вам необходимо использовать поисковую оптимизацию.

Save the page as trivia_quiz.htm. That completes the definition of our quiz's questions and answers. In the next chapter we can move on to write code that checks the answers of the questions against the answers supplied by the user.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©

R7