I am (still) trying to program a quiz, where all the questions have a 'question' class and the answers within the questions have an 'answer' class, together with a 'correct' or 'incorrect' class.
After some help from stackoverflow, the program now successfully loops through all the possible answers, setting up addEventListeners for each answer button that wait for a click. When clicked, I want to increase the counter of either the right or wrong answers by one.
My problem is that the change in the counter variables is not persistent. It does go from 0 to 1, as intended, but when I click the next answer, it AGAIN goes from 0 to 1. It looks like a scope problem, but I just do not see how it could be, unless I misunderstood something pretty basic about JavaScript syntax...
let right = 0;
let wrong = 0;
let questions = document.querySelectorAll('.question');
let q = questions.length;
for (let k = 0; k < q; k++) {
let right_answer = questions[k].querySelector('.answer.correct');
let wrong_answers = questions[k].querySelectorAll('.answer.incorrect');
right_answer.addEventListener('click', function() {
right++;
alert(right);
return false;
});
let len = wrong_answers.length;
for (let l = 0; l < len; l++) {
wrong_answers[l].addEventListener('click', function() {
wrong++;
alert(wrong);
return false;
});
}
}
<h2>Quiz Time!</h2>
<a href="index.html">Take me back.</a>
<p>Question 1?</p>
<form class='question' onsubmit='return false'>
<button class='answer correct'>right</button>
<button class='answer incorrect'>wrong</button>
<button class='answer incorrect'>wrong</button>
</form>
<p>Question 2?</p>
<form class='question' onsubmit='return false'>
<button class='answer correct'>right</button>
<button class='answer incorrect'>wrong</button>
<button class='answer incorrect'>wrong</button>
</form>
(the alert statements are just to check the values)
No matter what I do, the right++ and wrong++ commands just seem to have no persistent effect outside the scope of their respective addEventListener. Can anyone make me see the light...? ;-)
EDIT: I added a minimal version of my html. No matter how many buttons I click, the alert is always "1".
EDIT2: I tried to include a "return false" in the functions, which is how I understood a suggested solution, but this did not solve the problem.
final EDIT: edited the code to incorporate the solution.