Making MCQ quiz in javascript

Making MCQ quiz in javascript

Hey there, Javascript developers 👩‍💻

In this article, we are going to see how to make a simple quiz (MCQ) in javascript !!

Problem Statement

Prepare a Quiz and enable the user to play the quiz and calculate scores based on the answers chosen by the user.

Tech Stack Used

Html, CSS, and Javascript. This is beginner friendly application that any newbie can try to make the concept more clear and for good coding practice.

okay, this sounds interesting but the question is where to start?

  • I prefer to build the HTML part at first so that we can get an idea about the app which we are going to develop.

  • then develop a javascript file to form logic around the application and to make sure that wiring between HTML file and javascript file is good for that you can do a dry run by using console log.

  • and last I prefer to do css part because I am not good at css but you can do it simultaneously. so let's start coding with the first HTML file

      <form id="quiz-form">
          <div>
              <h2 >Triangle Quiz</h2>
              <p>1. What is the third angle for the triangle where angle1 = 45° and angle2 = 
               45°?</p>
          </div>
      </form>
    

Here I am using the form element to make a quiz because in javascript form element is used as a documenting section for submitting information. nowhere inside the form element, ideal practice is making separate div element for every new question. you will see ahead why I am saying this.

now as this is MCQ quiz we need 4 options. to give options we are using input element but in input, we are using type as "radio".

why type="radio"

because radio represents the collection of radio buttons describing related options.

Note 1: radio buttons of all options should share the same name.

Note 2: The value attribute defines the unique value associated with each radio button. The value is not shown to the user but is the value that is sent to the server on "submit" to identify which radio button was selected.

Note 3: Always add the tag for best accessibility practices!

<form id="quiz-form" >
        <div>
            <h2 >Triangle Quiz</h2>
            <p>1. What is the third angle for the triangle where angle1 = 45° and angle2 = 45°?</p>
            <label><input type="radio" name="question1" value="45°"/>45°</label>
            <label><input type="radio" name="question1" value="60°"/>60°</label>
            <label><input type="radio" name="question1" value="90°"/>90°</label>
        </div>

    </form>

now we have the question format ready we can make quiz of any number of questions. Tip:remember to change the name tag inside the input tag for every question so that it toggles for only that question.

now let's create a button to submit our test.

<button id="submit-btn" >Submit Answers</button>

Remember write button element outside the form because if we click on button page gets refreshed. so to make it simple let's write a button element outside the form element.

and last we are going to make another div for our final result.

<div id="output"></div>

Now we are done with the HTML part let's move towards the javascript part.

Select the elements using querySelector

var quizForm=document.querySelector("#quiz-form");
var submitBtnEl=document.querySelector("#submit-btn");
var outputEl=document.querySelector("#output")

This was an easy task to select all the elements from HTML file to move ahead with the javascript file.

Now we are going to make a separate array of correct answers to check whether user has selected the correct answer or not Note:always use exact same value of the correct answer which we have already written in HTML. because this wiring compares array elements with an answer which you have chosen.

correctAnswers=["90°","right angled"]

Now we are going to write a logical part of code that's functions which will lead us to calculate the score of every user.

now lets make button clickable.

for that, we are using addeventlistener on the button. on click call function.

submitBtnEl.addEventListener("click",calculateMarks)

Create a function

function calculateMarks(){
    let score=0;
    let index=0;
    const forResults= new FormData(quizForm);
    for (let forResult of forResults.values()){
        if (forResult==correctAnswers[index]){
            score=score+1;
        }
        index=index+1;

    }

    outputEl.innerText="Your score is "+score;
}

In the above calculateMarks function, we have initialised score and index = 0, because we are going to use that ahead to iterate through loop and array respectively. Now we are using form element in HTML so that now we can use new FormDate which is an inbuilt API for the form element.

also in for loop, we are using for-of because it does not only gives us an index but it gives the value of that index from the given array. in this case, we will be getting/comparing correct answers with the user's answers.

syntax for that is:

const forResults= new FormData(quizForm);
    for (let forResult of forResults.values()){
        if (forResult==correctAnswers[index]){
            score=score+1;
        }

so this was the javascript part after this you can add as many questions as you can and also you can make css as you like... thank you