In my code, I have many questions. After submission, I would like to change the colour of the question to green if it was correct, or red if it was wrong.
document.getElementById("submit-button").addEventListener("click", function() {
var questions = document.getElementsByClassName("question");
var totalQuestions = questions.length;
var correctAnswers = 0;
for (var i = 0; i < questions.length; i++) {
var question = questions[i];
var selectedOption = question.querySelector("input:checked");
if (selectedOption) {
var answer = selectedOption.value;
var correctAnswer = question.getAttribute("data-correct-answer");
if (answer === correctAnswer) {
correctAnswers++;
}
}
}
var resultMessage = "You answered " + correctAnswers + " out of " + totalQuestions + " questions correctly.";
alert(resultMessage);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="question" data-correct-answer="c">
<p>Question 1:</p>
<p>What is the value of 2 + 2?</p>
<label><input type="radio" name="q1" value="a"> a) 2</label>
<label><input type="radio" name="q1" value="b"> b) 3</label>
<label><input type="radio" name="q1" value="c"> c) 4</label>
</div>
Can anyone please tell me how to do this?
I have tried using ChatGPT (which was pretty useless) and the internet. ChatGPT didn't understand the question and there was nothing on the internet to help.
You could apply the style change with a dynamic class like .correct
and .incorrect
for answers that are correct or incorrect.
The style definitions might look like:
<style>
.correct {
color: green;
}
.incorrect {
color: red;
}
</style>
and then in your script:
(...)
if (selectedOption) {
var answer = selectedOption.value;
var correctAnswer = question.getAttribute("data-correct-answer");
if (answer === correctAnswer) {
correctAnswers++;
/* add class here, if correct */
question.classList.add("correct");
} else {
/* add class here, if incorrect */
question.classList.add("incorrect");
}
}
}
(...)