Objects in JavaScript

Am I doing Correct

const question1 = 'Which is not a mortality indicator?'
let multiPle = {
  question1: { option: ['Years of potential life lost',
'Life expectancy','IMR', 'Prevalence'],
              CorrAns: 'Prevalence'}
  // multiple chocie questions, can it put in this manner as object 
  /*Which is not a mortality indicator? 
  than  option 
  a.Years of potential life lost
b. Life expectancy
c. IMR
d. Prevalence   */

how we can select correct answer/s

Basically you should iterate over multiple.question1.option using multiple.question1.option.map(yourCallback), creating a button or a selector from each array’s item and add for each of them a function in onClick html attribute which accepts a button’s name html attribute (which should contain a text of the array’s corresponding item) and inside of it compare event.target.name to multiple.question1.CorrAns.

If it isn’t a sufficient explanation, let me know.

1 Like

Hi I am stuck here it should give score of 5, if I select all correct answers , it is giving me 4 instead , what is wrong I am doing ?

 window.onload = function () {
  show(0);
};
//question
let questions = [
  {
    id: 1,
    question:
      "Which one of the following does not represent the submerged portion of the iceberg?",
    answer: "Diagnosed cases under treatment",
    options: [
      "Diagnosed cases under treatment",
      "Undiagnosed cases",
      "Pre-symptomatic cases",
      "Carriers sub clinical cases",
    ],
  },
  {
    id: 2,
    question:
      "Which of the following is NOT true regarding pathogenesis of a disease?",
    answer: "Screening is of no use in changing course of disease",
    options: [
      "Screening is of no use in changing course of disease",
      "Tertiary prevention is possible",
      "Entry of organism occurs",
      "Includes subclinical cases",
    ],
  },
  {
    id: 3,
    question: "In Advanced Epidemiological triad, agent is replaced by:",
    answer: "Causative factors",
    options: [
      "Determinant risk factors",
      "Causative bacterium/virus",
      "Causative factors",
      "Determinant factors",
    ],
  },
  {
    id: 4,
    question: "Triangle of Epidemiology stands for:",
    answer: "Interaction & interdependence of agent, host, environment & time",
    options: [
      "Interaction of agent, host & environment",
      "Interaction of agent, host, environment & time",
      "Interaction & interdependence of agent, host, environment & time",
      "None of the above",
    ],
  },
  {
    id: 5,
    question: "Epidemiological triad are all included except:",
    answer: "Investigator",
    options: ["Host", "Environmental factors", "Agent", "Investigator"],
  },
];
function submitForm(e) {
  e.preventDefault();
  let name = document.forms["welcome_form"]["name"].value;
  //save user name
  sessionStorage.setItem("name", name);
  location.href = "quiz.html";
}
let question_count = 0;
let points = 0;
function next() {
  let userAnswer = document.querySelector("li.options.active").innerHTML;
  //check answer and give points
  if (userAnswer === questions[question_count].answer) {
    points += 1;
    sessionStorage.setItem('points', points);
  }
  if (question_count === questions.length - 1) {
    sessionStorage.setItem('time',`${minutes} minutes and ${seconds} seconds`)
    clearInterval(myTime);
    return (location.href = "end.html");
  }

  question_count++;
  show(question_count);
}
function show(count) {
  let question = document.getElementById("questions");
  // question.innerHTML="<h2>" + questions[count].question + "</h2>";
  question.innerHTML = `<h2>Q ${question_count + 1} ${
    questions[count].question
  }</h2>
    <ul class="option_group">
    <li class="options">${questions[count].options[0]}</li>
    <li class="options">${questions[count].options[1]}</li>
    <li class="options">${questions[count].options[2]}</li>
    <li class="options">${questions[count].options[3]}</li>
    </ul>`;
  toggleActive();
}
let toggleActive = () => {
  let options = document.querySelectorAll("li.options");
  for (let i = 0; i < options.length; i++) {
    options[i].onclick = function () {
      for (let j = 0; j < options.length; j++) {
        if (options[j].classList.contains("active")) {
          options[j].classList.remove("active");
        }
      }
      options[i].classList.add("active");
    };
  }
};

Since I can’t test your code - it lacks all the needed files - place debugger or console.log
like this:

if (userAnswer === questions[question_count].answer) {
    points += 1;
    debugger;
    // or
    // console.log(`userAnswer: ${userAnswer}`);
    // console.log(`questions[question_count].answer: ${questions[question_count].answer}`);
    // console.log(`points: ${points}`);
    sessionStorage.setItem('points', points);
  }

and look what’s happening in here.

debugger is a powerful tool which allows you to see everything what’s happening within the scope you put it into. Put it in the scope you suspect to contain the reason of malfunction, open developer tools in your browser, do user actions that will provoke this code to be called, and when everything stops just move your mouse over the variables and parameters to see their contents.

Otherwise - classical console.log will do.

thank you
it says inner html cant be null !

pls also find the actual app
https://drnareshchauhan.netlify.app/

One of errors occur here at the starting screen

Another thing that I’ve noticed is that points do not increase only on the 4th question. Although strings in your questions object match.

You can watch points in your local storage in this Devtools tab after every successful answer to verify this.

i removed that question and it works but didn’t get what was wrong with that question
anyway thanks!

Glad it helped. I’d suggest to try putting debugger; in presumably malfunctioning place of code.

The general approach is to place it somewhere and see - does code reach this debugger (you can see it by the page enabling the debugger mode). If yes - all the previous code worked and the problem is deeper. Then place it in the next place and see whether the code reaches that place.

Also debugger is extremely useful to see values in the scope where you put debugger;

1 Like