Search code examples
javascriptarraysjavascript-objects

How to update a variable value returned from a function


This is my Quiz code for javascript:

"use strict"
const questions = [
  {
    question: "whats the full form of HTML",
    answers: {
      a: "Hello Text My Language",
      b: "Hyper text Main Language",
      c: "Hyper Text Markup Language",
      d: "Hi There My Luck",
    },
    correctAnswer:"ent-c",
  },
  {
    question: "whats the full form of CSS",
    answers: {
      a: "Cascading Style Sheet",
      b: "City Site Section",
      c: "Cyber Section Stand",
      d: "CycleStand Section",
    },
    correctAnswer:"ent-a",
  },
  {
    question: "whats the full form of JSON",
    answers: {
      a: "Jest Oriented Note",
      b: "JavaScript Object Notation",
      c: "Javascript Organised Node",
      d: "Joomla Of Node",
    },
    correctAnswer:"ent-b",
  },
  {
    question: "whats the full form of SQL",
    answers: {
      a: "Super Query Language",
      b: "Sorted Queue Line",
      c: "Superior Query Language",
      d: "Structured Query Language",
    },
    correctAnswer:"ent-d",
  },
];

let quest = document.querySelector('.question');
let quizLIst = document.querySelector('.quiz');
const btn = document.querySelector('.submitBtn');
const scoreDiv = document.querySelector('.scoreCard');
let currentQuestion = 0;
let score=0;
const loadQuestion = () =>{
    quest.innerText="";
    quizLIst.innerHTML="";
    console.log(questions[currentQuestion].question);
    quest.innerText = questions[currentQuestion].question;
    const ansEntries = Object.entries(questions[currentQuestion].answers);
    for (const [getQ, getA] of ansEntries) {
        quizLIst.innerHTML += `
        <li><input type="radio" class="ansOptions" id="ent-${getQ}" name="ans" value="${getA}"/><label for="${getA}">${getA}</label></</li>
        `;
    }
}
loadQuestion();

const allAnss = document.querySelectorAll('.ansOptions');
let getCheckedAnswer = () =>{
    let answer="";
    allAnss.forEach((currAns) =>{
        if(currAns.checked){
            answer = currAns.id;   
        }
    });
    return answer;
}

btn.addEventListener('click', ()=> {
   let checkedAnswer =  getCheckedAnswer();
    console.log("checked answer is ", checkedAnswer);
    if(checkedAnswer === questions[currentQuestion].correctAnswer){
        console.log("right");   
        score++;
    } 
    else{
        console.log("wrong");
    }
    currentQuestion++;
    
    if(currentQuestion <= questions.length){
        loadQuestion();
    }
})

But somehow checkedAnswer variable is not getting updated. After first question, checkedAnswer value is not getting empty, therefore my next answers are stuck with the first answer. where can i empty the checkedAnswer value in the code, i tried doing it, but nothing seemed to be working


Solution

  • You need to get the current options contained in your .ansOptions. So you need to update getCheckedAnswer() for each question, as allAnss is still containing the old NodeList from the first question's options.

    "use strict"
    const questions = [
      {
        question: "whats the full form of HTML",
        answers: {
          a: "Hello Text My Language",
          b: "Hyper text Main Language",
          c: "Hyper Text Markup Language",
          d: "Hi There My Luck",
        },
        correctAnswer:"ent-c",
      },
      {
        question: "whats the full form of CSS",
        answers: {
          a: "Cascading Style Sheet",
          b: "City Site Section",
          c: "Cyber Section Stand",
          d: "CycleStand Section",
        },
        correctAnswer:"ent-a",
      },
      {
        question: "whats the full form of JSON",
        answers: {
          a: "Jest Oriented Note",
          b: "JavaScript Object Notation",
          c: "Javascript Organised Node",
          d: "Joomla Of Node",
        },
        correctAnswer:"ent-b",
      },
      {
        question: "whats the full form of SQL",
        answers: {
          a: "Super Query Language",
          b: "Sorted Queue Line",
          c: "Superior Query Language",
          d: "Structured Query Language",
        },
        correctAnswer:"ent-d",
      },
    ];
    
    let quest = document.querySelector('.question');
    let quizLIst = document.querySelector('.quiz');
    const btn = document.querySelector('.submitBtn');
    const scoreDiv = document.querySelector('.scoreCard');
    let currentQuestion = 0;
    let score=0;
    const loadQuestion = () =>{
        quest.innerText="";
        quizLIst.innerHTML="";
        console.log(questions[currentQuestion].question);
        quest.innerText = questions[currentQuestion].question;
        const ansEntries = Object.entries(questions[currentQuestion].answers);
        for (const [getQ, getA] of ansEntries) {
            quizLIst.innerHTML += `
            <li><input type="radio" class="ansOptions" id="ent-${getQ}" name="ans" value="${getA}"/><label for="${getA}">${getA}</label></</li>
            `;
        }
    }
    loadQuestion();
    
    let getCheckedAnswer = () =>{
        const allAnss = document.querySelectorAll('.ansOptions')
        let answer="";
        allAnss.forEach((currAns) =>{
            if(currAns.checked){
                answer = currAns.id;   
            }
        });
        return answer;
    }
    
    btn.addEventListener('click', ()=> {
       let checkedAnswer =  getCheckedAnswer();
        if(checkedAnswer === questions[currentQuestion].correctAnswer){
            console.log("right");   
            ++score;
        } else {
            console.log("wrong");
        }
        currentQuestion++;
        
        if(currentQuestion < questions.length){
            loadQuestion();
        }    
        document.querySelector('.scoreCard').innerText = 'Your score is ' + score + '.';
    })
    <div class="scoreCard"></div>
    
    <div class="question"></div>
    <div class="quiz"></div>
    <button class="submitBtn">answer</button>