Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Js code

. We are creating js multiple choice question

Screenshot of multiple choice question answer 

We creating a separate article element for each question and its answers. Here all the answer are creating through checkbox element.
Each checkbox value is the question number start from 0 and an answer value.

<input type=”checkbox” id=”options00″ value=”0:Modi” name=”option0″>Modi

We have two for loop, first is iterating through each question and second j for loop is for iterating through each answer options of that particular question.

<html>
<head>
	<script>
	function init(){
		var questions = '[{ "question":"Select names of India prime minister?", "options":["Modi", "Rahul Gandhi", "Nehru"], "answer":["Modi", "Nehru"]}, 
{"question":"What is second question?", "options":["Aloo", "Gobi"], "answer":["Gobi"]}]';

		var dataModel = JSON.parse(questions);
		for(i =0; i<dataModel.length;i++) {

			var article = document.createElement('article');
			article.innerHTML = "<p>" + dataModel[i].question + "</p>";

			for(j=0;j<dataModel[i].options.length;j++){
				var checkbox = document.createElement('input');
				checkbox.setAttribute("type","checkbox");
				checkbox.setAttribute("id","options" + i + "" + j);
				checkbox.setAttribute("value", i + ":" + dataModel[i].options[j]);
				checkbox.setAttribute("name","option" + i);

				var label = document.createElement("label");
				label.setAttribute("for","options" + i + "" + j);
				label.innerHTML = dataModel[i].options[j];

				var breakTag = document.createElement("br");

				article.append(checkbox);
				article.append(label);
				article.append(breakTag);
			}
			document.getElementById("questions").append(article);
	}
// end of i for loop
var button = document.createElement('button');
			button.innerHTML = "Submit";

			button.onclick = function(){
				var checkboxElements = document.querySelectorAll('[id^=options]');
				var score = 0;

				for(let i=0; i < checkboxElements.length; i++){
					if(checkboxElements[i].checked){
						var options = checkboxElements[i].value.split(":");
            var correctAnswer = dataModel[options[0]].answer.filter( (data) =>
              data === options[1]
            );

						if(correctAnswer.length >= 1)
							score++;
					}
				}
				console.log("Total answer score : ",score);

				showResults(score);
}

			var breakTag = document.createElement("br");
			document.getElementById("questions").append(breakTag);
			document.getElementById("questions").append(button);
	}

	function showResults(score){
		var scoreSection = document.getElementById("score");

    removeNodes(scoreSection);
    var article = document.createElement("article");
		article.innerHTML = "<p> You'r score is <b> " + score + "</b></p>";
		scoreSection.append(article);
	}

  function removeNodes(node){
    while (node.hasChildNodes())
      node.removeChild(node.lastChild);
  }

	window.onload = init;
	</script>
</head>
<body>
		<header>
			<center>Quiz Applcation</center>
		</header>
		<hr/>
		<section id="questions">
		</section>
		<section id="score">
		</section>
</body>
</html>

Once the user clicks on the submit button we will be iterating through each checkbox element list and check if checkbox click is the correct answer. This can be achieved when checkbox element is checked and then we have to use javascript split function to separate checkbox value contain question number and answer.
As value=”0:Modi”
Where 0 is the first question and Modi is a value of checkbox answer of that question.

var correctAnswer = dataModel[options[0]].answer.filter( (data) =>
   data === options[1]
);

In above code, we are iterating through each answer to that particular question and check if the answer is correct. For the first question, we have to iterate 3 times in answer and 2 iterations for the second answer. As the filter will create a new array containing correct checkbox answer.

showResults to create an element containing the score result and we have used the remove function to delete the existing score result node. So that duplication of score element will remove whenever a new score is created.

Js code

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top