I developed a simple quiz application in which the user selects an answer and then clicks the 'check' button. If the selected answer is correct, it will be highlighted in green while incorrect answers are highlighted in red. Conversely, if the wrong answer is chosen, the selected option turns red while the correct answer is highlighted in green.
Currently, my code displays all answers as either green (if correct) or red (if incorrect). How can I modify it to achieve the desired result described above?
<script>
let questionIndex = 0
let selectedAnswer
let correct
let incorrect
const quiz = [
{
question: 'What is the capital of France?',
correct_answer: 'Paris',
answers: ['Berlin', 'London', 'Madrid', 'Paris'],
}
]
const currentQuestion = quiz[questionIndex]
const correctAnswer = currentQuestion.correct_answer
const checkAnswer = () => {
if (selectedAnswer == correctAnswer) {
correct = true
}
else {
incorrect = true
}
}
</script>
<style>
.correct {
background-color: aquamarine;
}
.incorrect {
background-color: red;
}
</style>
<main>
<h3>{quiz[questionIndex].question}</h3>
<label class:correct class:incorrect>
<input
type="radio"
bind:group={selectedAnswer}
value={quiz[questionIndex].answers[0]} />
{quiz[questionIndex].answers[0]}
</label>
<label class:correct class:incorrect>
<input
type="radio"
bind:group={selectedAnswer}
value={quiz[questionIndex].answers[1]} />
{quiz[questionIndex].answers[1]}
</label>
<label class:correct class:incorrect>
<input
type="radio"
bind:group={selectedAnswer}
value={quiz[questionIndex].answers[2]} />
{quiz[questionIndex].answers[2]}
</label>
<label class:correct class:incorrect>
<input
type="radio"
bind:group={selectedAnswer}
value={quiz[questionIndex].answers[3]} />
{quiz[questionIndex].answers[3]}
</label>
<button on:click={checkAnswer}>Check</button>
</main>