Here, we’re not using any SQL database or php scripts. instead we’ll be Working with just arrays. Mostly multi dimensional arrays. Let’s begin our tutorial.
//Let's define our questions.
"what is the first letter of the english alphabet",
"how many numbers are between 1 and 10",
"How many letters are in the English alphabet"
//now we'll list our options.
var options =[
//Let's define an array of our answers.
// Let's create an empty array to store the answer the student picked.
Now we’ve stored our questions and options, let’s begin to display it on the screen giving the options radio buttons.
we’ll use the questions array as a reference array to know the number of items in all the arrays since they’re meant to have the same number of items.
//Let's create a div to wrap our questions and options with a id as wrapper.
//Let's add the question as a text node.
("question "+i+")"+ question[i]);
//Now append our text into the wrapper div.
//Now let's output the options in radio input tags.
//Let's create a new div to wrap our radio div.
//Now let's create a text node to display each option beside their corresponding radio button.
//let's now add our radio wrapper div into the main wrapper.
//Now let's add our wrapper in our container div.
In the above code, since the options array is two dimensional i.e array within a larger array, we looped it again to get the values inside the inner array and the code will continue till every single value is displayed.
Now let’s add our submit button to end the quiz.
Now let’s explain how the submit function will work. We’ll first select all the answers and store into our user answer array (the array we left empty) then we compare this array with our answer array for matches. Let’s get on with it shall we?
//Let's select all the checked inputs.
var user= document. querySelectorAll("input :checked");
//This selects all the checked answers. Now let's add them to the array.
//Now that we've arranged them in the array, let's write a code to compare the two arrays for similarities.
"You scored "+correct+" out of "+answers.length;
Note: all questions must be answered before submitting the test. If not the marker will be confused. You can avoid this by adding a fifth option with type hidden and value as “no answer” with a selected attribute so that option will be selected at default. Here’s an example.
This gives every question a default answer which can’t be seen.
Hope you enjoyed this article, you can leave your feedback in the comment if this post helped you. Also feel free to contact us via email