I am trying to develop a simple Javascript function which highlights the chosen answer to red if the answer is incorrect, and green if correct. If another incorrect answer is chosen, the previous incorrect answer must switch to neutral background and the new incorrect answer must be in red. Also we must have the same functionality for multiple questions - the red and green for previous questions must remain as we move on to new questions.
I have an example here, but can someone help me add the above functionality?
HTML:
1. A sum of money is to be distributed among P, Q, R, and S in the proportion 5:2:4:3 respectively. If R gets ₹1000 more than S, what is the share of Q (in ₹)?
<div id="item" > </div>
<button id="incorrect" class="btn" name="q1" onClick="click_action();"> 500</button>
<button id="incorrect" class="btn" name="q1" onClick="click_action();"> 1000</button>
<button id="incorrect" class="btn" name="q1" onClick="click_action();"> 1500</button>
<button id="correct" class="btn" name="q1" onClick="click_action();"> 2000</button>
<br><br>
2. A trapezium has vertices marked as P, Q, R and S (in that order anticlockwise). The side PQ is parallel to side SR. Further, it is given that, PQ = 11 cm, QR = 4 cm, RS = 6 cm and SP = 3 cm. What is the shortest distance between PQ and SR (in cm)?
<br>
<div id="answer-buttons" class="btn-grid">
<button id="correct" class="btn" name="q2" onClick="click_action();"> 1.80 </button>
<button id="incorrect" class="btn" name="q2" onClick="click_action();"> 2.40 </button>
<button class="btn" id="incorrect" name="q2" onClick="click_action();"> 4.20 </button>
<button class="btn" id="incorrect" name="q2" onClick="click_action();"> 5.76 </button>
</div>
CSS
.btn {
--hue: var(--hue-neutral);
border: 10px solid hsl(var(--hue), 100%, 30%);
background-color: blue;
border-radius: 100px;
padding: 10px 30px;
color: white;
outline: none;
}
.btn-grid {
display: grid;
grid-template-columns: repeat(2, auto);
gap: 10px;
margin: 20px 0;
}
JS
function click_action() {
var incorrect = document.getElementById("incorrect");
var correct = document.getElementById("correct");
if (incorrect.style.background != "red") {
incorrect.style.background = "red";
}
else if (correct.style.background != "green") {
correct.style.background = "green";
}
}