I try to build a quiz of 30 questions with dynamically generated elements.
The html:
<div class="secondBox">
<div class="questionBox">
</div>
</div>
Here's my script:
function showQuestion(){
for(let i = 0; i < QuesPartA.length; i++){
$(".questionBox").append('<div class="Question">Number '+ parseInt(i+1) +'</div>');
QuesPartA[i]['option'].forEach(option => {
$(".questionBox").append('<span class="pilihan">'+option +' </span><br>');
});
}
$(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>');
};
$(".questionBox").on("click", ".pilihan", function() {
$(this).css("background", "red");
$('.pilihan').not(this).css("background", "#ccc");
So the dynamically generated element will show 30 questions with four answer options each. I want to change the color of the option to be red once the user clicks, plus with the ability to change choice.
I can do that with the code above: I can choose an answer for question number 1 (one of the options change to red), but when I click an answer for number 2, the chosen option in question 1 goes back to #ccc color. It goes the same way when I choose an option in question 3, the chosen answers for number 2 and 1 go back to #ccc.
Does anyone have any ideas so that everytime I click an answer for the next question the previous ones remain red?
Thanks in advance.
I believe that the .not() always fails in this line:
$('.pilihan').not(this).css("background", "#ccc");
Which results in the background being changed to #ccc.
Try just removing that whole line...
$('.pilihan').not(this).css("background", "#ccc");
This should also cause any line that was turned red to remain red.