I’m working on a quiz app where students need to pick multiple correct answers using checkboxes. I want to check if the right checkboxes are selected before showing feedback to the user.
The problem is that my condition always goes to the else block, even when I select exactly those two checkboxes. No matter how I change the if condition, it keeps executing the else part.
Here’s how I get the elements:
var quizContainer = document.getElementById('quiz-form');
var questionElements = quizContainer.getElementsByTagName('p');
checkboxList = questionElements[0].getElementsByTagName('input');
var submitBtn = document.getElementById('submit-btn');
What could be wrong with my checkbox checking logic?
yeah, classic timing issue. ur checking those checkboxes before the user even clicks them, so they’re all false. also, why loop through them if ur just gonna hardcode [0] and [1]? just run ur validation when they hit submit, not on page load.
The problem’s timing - your validation runs when the page loads, not when users click checkboxes. At that point, nothing’s checked yet, so it fails and sets onclick to displayWrongFeedback. Even when users check boxes later, the onclick handler stays the same. Had this exact issue last year building a certification quiz. Move your validation inside the submit button’s click event. Also, that for loop does nothing since you’re hardcoding checkboxList[0] and checkboxList[1] instead of using j. Ditch the loop and do: submitBtn.onclick = function() { /* validation logic here */ }. Now it checks the actual checkbox states when users hit submit.
You’re setting the onclick handler inside the loop, so it gets overwritten each time. Move your checkbox validation into the click handler instead. This approach worked for me: submitBtn.onclick = function() { if(checkboxList[0].checked && checkboxList[1].checked) { displayCorrectFeedback(); } else { displayWrongFeedback(); } }; Ditch the for loop - you’re only checking indexes 0 and 1 anyway. Right now your condition runs when the page loads, not when users actually click the checkboxes.