Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

JavaScript How can I change this to highlight one answer when its correct?

Lionviper007

New Coder
HTML:
<html>
    <head>
       <title>Country Quiz</title>
    <link rel="stylesheet" href="Quiz.css" />
    <link
      href="[URL]https://fonts.googleapis.com/css?family=Notable|Roboto&display=swap[/URL]"
      rel="stylesheet"
    />
       
    </head>

    <body>
        <h1>Quiz on Important Facts</h1>
<div class="quiz-container">
  <div id="quiz"></div>
</div>
<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>
<div id="results"></div>
        <script>
            (function(){
  // Functions
  function buildQuiz(){
    // variable to store the HTML output
    const output = [];

    // for each question...
    myQuestions.forEach(
      (currentQuestion, questionNumber) => {

        // variable to store the list of possible answers
        const answers = [];

        // and for each available answer...
        for(letter in currentQuestion.answers){

          // ...add an HTML radio button
          answers.push(
            `<label>
              <input type="radio" name="question${questionNumber}" value="${letter}">
              ${letter} :
              ${currentQuestion.answers[letter]}
            </label>`
          );
        }

        // add this question and its answers to the output
        output.push(
          `<div class="slide">
            <div class="question"> ${currentQuestion.question} </div>
            <div class="answers"> ${answers.join("")} </div>
          </div>`
        );
      }
    );

    // finally combine our output list into one string of HTML and put it on the page
    quizContainer.innerHTML = output.join('');
  }

  function showResults(){

    // gather answer containers from our quiz
    const answerContainers = quizContainer.querySelectorAll('.answers');

    // keep track of user's answers
    let numCorrect = 0;

    // for each question...
    myQuestions.forEach( (currentQuestion, questionNumber) => {

      // find selected answer
      const answerContainer = answerContainers[questionNumber];
      const selector = `input[name=question${questionNumber}]:checked`;
      const userAnswer = (answerContainer.querySelector(selector) || {}).value;

      // if answer is correct
      if(userAnswer === currentQuestion.correctAnswer){
        // add to the number of correct answers
        numCorrect++;

        // color the answers green
        answerContainers[currentQuestion].style.color = 'lightgreen';
      }
      // if answer is wrong or blank
      else{
        // color the answers red
        answerContainers[questionNumber].style.color = 'red';
      }
    });

    // show number of correct answers out of total
    resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
  }

  function showSlide(n) {
    slides[currentSlide].classList.remove('active-slide');
    slides[n].classList.add('active-slide');
    currentSlide = n;
    if(currentSlide === 0){
      previousButton.style.display = 'none';
    }
    else{
      previousButton.style.display = 'inline-block';
    }
    if(currentSlide === slides.length-1){
      nextButton.style.display = 'none';
      submitButton.style.display = 'inline-block';
    }
    else{
      nextButton.style.display = 'inline-block';
      submitButton.style.display = 'none';
    }
  }

  function showNextSlide() {
    showSlide(currentSlide + 1);
  }

  function showPreviousSlide() {
    showSlide(currentSlide - 1);
  }

  // Variables
  const quizContainer = document.getElementById('quiz');
  const resultsContainer = document.getElementById('results');
  const submitButton = document.getElementById('submit');
  const myQuestions = [
   
 
  {
    question: "1.What is the Capital of AFGHANISTAN?",
    answers: {
      a: 'Vienna',
      b: 'Kaubl',
      c: 'Baku',
      d:'Tokyo'
    },
    correctAnswer: 'b'
  },
  {
    question: "2.What is the Capital of ALBANIA?",
    answers: {
      a: 'Zagreb',
      b: 'Islamabad',
      c: 'Tirana',
      d:'Muscat'
    },
    correctAnswer: 'c'
    },
  {
    question: "3.What is the Capital of ALGERIA",
    answers: {
      a: 'Algiers',
      b: 'Port-au-Prince',
      c: 'Jerusalem',
      d:'Valletta'
    },
    correctAnswer: 'a'
    },
  {
    question: "4.What is the Capital of ANDORRA",
    answers: {
      a: 'Dhaka',
      b: 'Conakry',
      c: 'Andorra La Vella',
      d:'Kathmandu'
    },
    correctAnswer: 'c'
    },
  {
    question: "5.What is the Capital of ANGOLA",
    answers: {
      a: 'Podgorica',
      b: 'Managua',
      c: 'Bern',
      d:'Luanda'
    },
    correctAnswer: 'd'
    },
  {
    question: "6.What is the Capital of ANTIGUA & BARBUDA",
    answers: {
      a: 'Male',
      b: "Saint John's",
      c: 'Amman',
      d:'Lisbon'
    },
    correctAnswer: 'b'
     },
  {
    question: "7.What is the Capital of ARGENTINA",
    answers: {
      a: 'Ottawa',
      b: "Santiago",
      c: "Nuku'alofa",
      d:'Buenos Aires'
    },
    correctAnswer: 'd'
    },
  {
    question: "8.What is the Capital of ARMENIA",
    answers: {
      a: 'Panama City',
      b: "Port-Vila",
      c: "Yerevan",
      d:'Djibouti'
    },
    correctAnswer: 'c'
    },
  {
    question: "9.What is the Capital of AUSTRALIA",
    answers: {
      a: 'Brussels',
      b: "Canberra",
      c: "Dhaka",
      d:'Oslo'
    },
    correctAnswer: 'b'
    },
  {
    question: "10.What is the Capital of AUSTRIA",
    answers: {
      a: 'Kigali',
      b: "Jerusalem",
      c: "Beirut",
      d:'Vienna'
    },
    correctAnswer: 'd'
    },
  {
    question: "11.What is the Capital of AZERBAIJAN",
    answers: {
      a: 'Bangui',
      b: "Freetown",
      c: "Baku",
      d:'Asmara'
    },
    correctAnswer: 'c'
    },
  {
    question: "12.What is the Capital of BAHAMAS",
    answers: {
      a: 'Nassau',
      b: "Athens",
      c: "Yerevan",
      d:'Madrid'
    },
    correctAnswer: 'a'
     },
  {
    question: "13.What is the Capital of BAHRAIN",
    answers: {
      a: 'Abu Dhabi',
      b: "Manama",
      c: "Tehran",
      d:'Cairo'
    },
    correctAnswer: 'b'
    },
  {
    question: "14.What is the Capital of BANGLADESH",
    answers: {
      a: 'Dhaka',
      b: "Amsterdam",
      c: "Podgorica",
      d:'Dublin'
    },
    correctAnswer: 'a'
    },
  {
    question: "15.What is the Capital of BARBADOS",
    answers: {
      a: 'Guatemala City',
      b: "Windhoek",
      c: "Antananarivo",
      d:'Bridgetown'
    },
    correctAnswer: 'd'
     },
  {
    question: "16.What is the Capital of BELARUS",
    answers: {
      a: 'Guatemala City',
      b: "Windhoek",
      c: "Antananarivo",
      d:'Bridgetown'
    },
    correctAnswer: 'd'
     },
  {
    question: "17.What is the Capital of BELGIUM",
    answers: {
      a: 'Brussels',
      b: "Panama City",
      c: "Monrovia",
      d:'Bangkok'
    },
    correctAnswer: 'a'
     },
  {
    question: "18.What is the Capital of BELIZE",
    answers: {
      a: 'Podgorica',
      b: "Baghdad",
      c: "Helsinki",
      d:'Belmopan'
    },
    correctAnswer: 'd'
     },
  {
    question: "19.What is the Capital of BENIN",
    answers: {
      a: 'Canberra',
      b: "Sao Tome",
      c: "Porto-Novo",
      d:'Nicosia'
    },
    correctAnswer: 'c'
     },
  {
    question: "20.What is the Capital of BHUTAN",
    answers: {
      a: 'Georgetown',
      b: "Thimphu",
      c: "Chisinau",
      d:'Port Moresby'
    },
    correctAnswer: 'b'
     },
  {
    question: "21.What is the Capital of BOLIVIA",
    answers: {
      a: 'Conakry',
      b: "Sucre",
      c: "Kigali",
      d:'Bratislava'
    },
    correctAnswer: 'b'
     },
  {
    question: "22.What is the Capital of BOSNIA & HERZEGOVINA",
    answers: {
      a: 'Budapest',
      b: "Lome",
      c: "Sarajevo",
      d:'Port-au-Prince'
    },
    correctAnswer: 'c'
     },
  {
    question: "23.What is the Capital of BOTSWANA",
    answers: {
      a: 'Gaborone',
      b: "Luanda",
      c: "Porto-Novo",
      d:'Riyadh'
    },
    correctAnswer: 'a'
     },
  {
    question: "24.What is the Capital of BRAZIL",
    answers: {
      a: 'Dhaka',
      b: "Brasilia",
      c: "Beijing",
      d:'Stockholm'
    },
    correctAnswer: 'b'
     },
  {
    question: "25.What is the Capital of BRUNEI",
    answers: {
      a: 'Sofia',
      b: "Monrovia",
      c: "Bandar Seri BegAwan",
      d:'Pretoria, Cape Town, Bloemfontein '
    },
    correctAnswer: 'c'
     },
 
     
];

  // Kick things off
  buildQuiz();

  // Pagination
  const previousButton = document.getElementById("previous");
  const nextButton = document.getElementById("next");
  const slides = document.querySelectorAll(".slide");
  let currentSlide = 0;

  // Show the first slide
  showSlide(currentSlide);

  // Event listeners
  submitButton.addEventListener('click', showResults);
  previousButton.addEventListener("click", showPreviousSlide);
  nextButton.addEventListener("click", showNextSlide);
})();

        </script>
    </body>
</html>
 
Last edited by a moderator:
To highlight the correct answer when it is selected, you can add a class to the label element of the correct answer.

For example, you can add a class called "correct" to the label element of the correct answer in the following way:

Code:
// and for each available answer...
for(letter in currentQuestion.answers){
  // ...add an HTML radio button
  let answer = `<label>
                  <input type="radio" name="question${questionNumber}" value="${letter}">
                  ${letter} :
                  ${currentQuestion.answers[letter]}
                </label>`;
  // if this answer is the correct answer, add the correct class to the label element
  if (letter === currentQuestion.correctAnswer) {
      answer = `<label class="correct">
                  <input type="radio" name="question${questionNumber}" value="${letter}">
                  ${letter} :
                  ${currentQuestion.answers[letter]}
                </label>`;
  }
  answers.push(answer);
}

Then, you can use CSS to style the label element with the "correct" class. For example:

Code:
label.correct {
  color: green;
}

This will cause the label element of the correct answer to be highlighted in green when it is selected.
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom