0

I'll leave you a JDfiddle right up here.

JS fiddle

I'm trying to create a quiz in JS, getting the questions and answers from JSON.

    checkbox.addEventListener('change', function() {
      if (this.checked) {
        console.log("checkbox " + i + " checked")
        label.setAttribute("class", "richtig")
      } else {
        console.log("checkbox " + i + " unchecked")
        label.removeAttribute("class")
      }})

The EventListeners are setup like this - they differ a little depending on the input type. For now, it's supposed to add the class "richtig" to each checkbox's label that's selected, which sets the background color to lightgreen.
What it does instead is, adding the class to the last of the possible answers, no matter which is selected. This is for all three of the selectors, the checkboxes, radios, and selection.
The console.log also always logs for the last answer, even if checkbox 1 or 2 are selected, it logs "checkbox 3 checked".

And finally, the list selection behaves completely unexpected (to me). When clicking it, it'll instead of "selection i checked", log "selection i unchecked" and it'll do it for the amount of answers possible.
Also when the last option of a select option is selected, the color doesn't change to green, eventhough the class is correctly set.

Ultimatly, i'd want to grab the solution from the JSON, compare it to the selected answer and only color it, if it's actually correct. But i'm going to do that on my own, i just need help to select and modify the correct label.

Bonus: As you can see in the fiddle, i get the error "Uncaught TypeError: Cannot read property 'question' of undefined", eventhough it works without any issue. If someone knew why that is, that'd be neat.

Thanks everyone reading this and trying to help me,
have a nice day!

DerEd
  • 70
  • 6

1 Answers1

1
  • A select does not have a checked attribute
  • quizDyn.length is several hundred chars. It is not the array but the JSON string
  • Parse quizDyn ONCE and use the quizDyn instead of JSON.parse(quizDyn)[i]

Also many times you get the answer list. Just get it once. And reuse the var

Lastly you have a closure problem - I suggest you use data attributes on the elements or just use this.name

Here is a start

https://jsfiddle.net/mplungjan/q23bnef4/

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    Thank you! The parsing once at the beginning definitly makes more sense than what i did. – DerEd Jun 18 '21 at 14:18