I am trying to generate a quiz that will display three random questions, from an array of 6, when ever the page is reloaded.
The quiz works but displays all of the questions in the same order and I am looking to have only 3 random questions
The code I am using is as follows:
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
["Question 1", "1", "2", "3", "C"],
["Question 2", "X", "Y", "Z", "B"],
["Question 3", "4", "5", "6", "C"],
["Question 4", "A", "B", "C", "A"],
["Question 5", "7", "8", "9", "B"],
["Question 6", "M", "N", "O", "A"]
];
function get(x){
return document. getElementById(x);
}
function renderQuestion(){
test = get("test");
if(pos >= questions.length){
test.innerHTML = "You got " +correct+ " of "+questions.length+" questions correct";
get("test_status").innerHTML = "Test Completed";
pos = 0;
correct = 0;
return false;
}
get("test_status").innerHTML = "Question " + (pos+1) + " of " + questions.length;
question = questions[pos] [0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
test.innerHTML = "" +question+" <br>";
test.innerHTML += "<input type='radio' name ='choices' value ='A'> " +chA+"<br>";
test.innerHTML += "<input type='radio' name ='choices' value ='B'> " +chB+"<br>";
test.innerHTML += "<input type='radio' name ='choices' value ='C'> " +chC+"<br><br>";
test.innerHTML += "<button onclick='checkAnswer()' >Submit Answer</button>";
}
function checkAnswer(){
choices = document.getElementsByName('choices');
for (var i = 0; i < choices.length; i++) {
if(choices[i].checked){
choice = choices[i].value;
}
}
if (choice == questions [pos][4]) {
correct++;
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);