Home > Net >  Quiz Game: How do i only allow one answer to be entered?
Quiz Game: How do i only allow one answer to be entered?

Time:05-29

I'm working on a quiz game, right now I'm trying to understand how I can remove the ability to select another option after one has already been clicked. As of right now, when you click an answer, if it's correct it will light up green or the wrong answer will light up red, while also lighting up the correct answer green regardless. but the problem is I can still click on the other options and they'll highlight red. can anyone help me with this?

Repository: https://github.com/JacobPacheco100/Quiz-Games

// BTN OPTION EVENT

options.forEach((op) => {
  op.addEventListener("click", (e) => {
    const choice = e.currentTarget;
    const choiceClass = e.currentTarget.classList;

    if (choiceClass.contains(answerList[currentQuestion])) {
      choice.style.backgroundColor = "green";
    } else {
      choice.style.backgroundColor = "red";
    }

    correct();
  });
});

// HIGHLIGHT CORRECT OPTION

function correct() {
  options.forEach((op) => {
    if (op.classList.contains(answerList[currentQuestion])) {
      op.style.backgroundColor = "green";
    }
  });
}

CodePudding user response:

I think, you should use "radio" type <input /> in the html file for the options. It will prevent to select multiple options. Remember to update javascript also. Ask if it is not clear to you.

CodePudding user response:

1.get rid off anonymous function inside AddEventListener

2.move code, that was inside anonymous function inside named function

  1. remove EventListener , if answer is correct
const checkAnswer = (e) => {


    const choice = e.currentTarget;
    const choiceClass = e.currentTarget.classList;

    if (choiceClass.contains(answerList[currentQuestion])) {
      choice.style.backgroundColor = "green";
    } else {
      choice.style.backgroundColor = "red";
    }

    correct();

}


options.forEach((op) => {
  op.addEventListener("click", checkAnswer);
});

// HIGHLIGHT CORRECT OPTION

function correct() {
  options.forEach((op) => {
    if (op.classList.contains(answerList[currentQuestion])) {
      op.style.backgroundColor = "green";
      op.removeEventListener("click", checkAnswer)
    }
  });
}


  • Related