Trivia quiz game - number of questions to display

logindices
Posts: 3

Trivia quiz game - number of questions to display

i'm trying to modify this code so that instead of displaying all questions in the json file, it displays only 10 per quiz. http://coursesweb.net/javascript/trivia-game-script_s2

MarPlo
Hi,
If you want to display the first 10 questions only, for JSON format, replace this line in the "trivia.js" file (line 118):

Code: Select all

nquizzes = quizzes.length;              // total number of quizzes

With this one:

Code: Select all

nquizzes = 10;

logindices
Thanks for that. but the random mode does not display question numbers above 5. it is only the first five questions that is randomized.question number 6,7,... are not displayed.
will like to display only 10 random questions from the possible lot.

MarPlo
Try this modification (I tested and it worked).
Replace these lines of code (115, ..., 118):

Code: Select all

var tobj = xhttp.responseText;         // puts in a variable the received data
tobj = tobj.replace(/\\|\r\n|\n|\r/gm, '');       // remove slashes "\" and new lines
eval("quizzes ="+ tobj);               // adds the JSON object in quizzes property
nquizzes = quizzes.length;              // total number of quizzes

With these code:

Code: Select all

quizzes = JSON.parse(xhttp.responseText);
nquizzes = quizzes.length;
var start_i = Math.floor(Math.random() * (nquizzes-10));
quizzes = quizzes.slice(start_i, start_i +10);
nquizzes = quizzes.length;

logindices
changed those lines but don't know why mine is not working. randomization worked. but in the random mode, i am allowed to answer all questions.
nquizzes=quizzes.length; appeared twice in the code u gave

MarPlo
Here's the logic of that code, in its comments:

Code: Select all

quizzes = JSON.parse(xhttp.responseText);  // gets object with all the questions from json string
nquizzes = quizzes.length;  // number of total questions
var start_i = Math.floor(Math.random() * (nquizzes-10));  // get a random number
quizzes = quizzes.slice(start_i, start_i +10);  // keep 10 questions
nquizzes = quizzes.length;  // actualizes the number of questions

So, the "quizzes" variable contains 10 questions only, and the second "nquizzes=quizzes.length;" actualizes the number of questions (10) in the "nquizzes" variable, after the line in which the slice() function keeps 10 questions in "quizzes".
According to this logic and code, the script not has more than 10 questions. Not know how you make the changes, and way it not works in your case.

Adv. Posts: 01

Similar Topics