Listener of events that is modifying the incorrect label

Here's a JSfiddle link for you to check out.

JS fiddle

I am currently attempting to build a quiz using JavaScript, where the questions and answers will be sourced from JSON data.

    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 event listeners are set up in such a way that they differ slightly based on the input type. Currently, the goal is to assign the class "richtig" to the label of each selected checkbox, changing the background color to light green.
However, instead of applying the class to the selected answer, it always applies it to the last possible answer, regardless of selection. This occurs across all three types of inputs: checkboxes, radios, and selections.
Additionally, the console log consistently displays information related to the last answer selected, even when checkboxes 1 or 2 are chosen, logging "checkbox 3 checked"

Moreover, the behavior of the list selection feature is quite unexpected. Clicking on an option logs "selection i unchecked" instead of "selection i checked," repeating this action for all available answers. Furthermore, even when selecting the last option in a select element, the color does not change to green even though the class is correctly applied.

In the end, my intention is to retrieve the correct solution from the JSON data, compare it to the user-selected answer, and only apply coloring if the response is accurate. However, I plan to tackle this task alone once I figure out how to properly select and modify the correct label.

Bonus: If you take a look at the fiddle, you may notice the error message "Uncaught TypeError: Cannot read property 'question' of undefined." Despite this error, everything seems to work as expected. Any insights into why this error occurs would be greatly appreciated.

Thank you to everyone who took the time to read this and offer assistance.
Wishing you all a wonderful day!

Answer №1

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

Additionally, retrieve the answer list only once. Reuse the variable for efficiency

Lastly, there seems to be a closure problem - I recommend using data attributes on the elements or simply utilizing this.name

Getting started with:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the technique for applying an image or texture to a specific section of a geometry in three.js?

In my three.js project, I successfully generated a sphere using SphereGeometry and applied a static color using MeshPhongMaterial. Now, I am looking to overlay an image onto the sphere in a specific area rather than wrapping it entirely around the object ...

establishConnection(); ^ TypeError: establishConnection is undefined

While attempting to connect to MongoDB, I encountered an error in my index.js file. require('dotenv').config(); const express = require('express') const app = express(); const cors = require('cors'); const connection = require ...

The API responded with JSON data enclosed in a function, causing an issue with parsing using json.loads

Dealing with JSON data that originates from the USGS Earthquake API has become a bit tricky. By visiting the provided link, you can view the raw JSON content. The JSON structure appears to be in good shape; however, there is an inconvenience with the resp ...

Show just a single error message if there are two validation errors present

In my AngularJS timepicker, users can choose multiple time segments for each day. The code has validation to detect duplicates and overlapping time segments. For example, entering 11:00am - 12:00am twice will trigger two error messages: 'Overlapping t ...

React encountered an unexpected end of JSON input while streaming JSON data

Currently, I am facing a challenge with streaming a large amount of data from a NodeJS server that retrieves the data from Mongo and forwards it to React. Due to the substantial volume of data involved, my approach has been to stream it directly from the s ...

Unusual display of feedback text in Bootstrap 4

When I directly copied this code snippet from Bootstrap 4: <div class="form-group has-danger"> <label class="form-control-label" for="inputDanger1">Input with danger</label> <input type="text" class="form-control form-contro ...

Node.js allows for the halting of statement execution if it exceeds a predetermined time limit

Is there a way to pause the execution of a statement if it exceeds a certain time limit? I need help with this problem. In the code snippet below, if the statement const result = await curly.get('www.google.com'); takes longer than 2 seconds to ...

Creating a single HTML file with multiple pages, each without a fixed navigation bar on the page

The main page will feature just a few buttons that will display specific content to the user. These buttons within #home will not be in the header, so they will only be visible on the #home section. <section id="home"> <a href="#content">co ...

Height of input-group-append and prepend in Bootstrap 4.0 is displayed incorrectly

Currently utilizing Bootstrap 4 and encountering an issue that I can't seem to resolve. The height of the input-group-append and input-group-prepend elements increases when screen resolution is decreased. You can view the problem in the following anim ...

In Reactjs, the specified property title is not found within the string type

Currently, I am working with Reactjs and using the nextjs framework. I have encountered an issue while fetching data where I am receiving an error message stating "Property 'title' does not exist on type 'string'". How can I r ...

The appsettings.json and appsettings.Release.json files fail to merge following the completion of the Azure DevOps CI pipeline for a .Netcore3.1 project

I am currently working on a .netcore 3.1 project that utilizes appsettings.json and appsettings.Release.json files for environment-specific configurations. https://i.sstatic.net/QHuiL.png Additionally, I have included the launchSettings.json file in my p ...

Mysterious Chrome glitch causes SVG element to shift down by 2 pixels

I am currently facing an issue with creating image links from an SVG spritesheet that is causing cross-browser problems between Chrome, Safari, and Firefox. Here are some of the anchor tags I am using: <a href="#" id="twitter-logo" class="socialIcon"&g ...

Exploring how Swift dictionaries match key values to index positions

My model enables me to execute the following code: print(crypto, name, price ?? 0.0, totalSupply ?? 0.0) // BTC Bitcoin 7639.39 17070625.0 // ETH Ethereum 590.943 99826611.0 // all 99 currencies I am currently required to print out details for all ...

Numerous Radio Buttons

I am currently working on creating a quiz similar to those found on Buzzfeed and Zimbio. I apologize if this question has been asked before, but despite my efforts in searching, I have not been able to find the answer I am looking for. In this quiz, partic ...

How can I simulate pressing the ENTER key in Selenium without selecting any element?

Having trouble using the firefox selenium plugin and sending the enter key after pasting text? The ENTER key press should not interact with any other element on the page, just a simple 'dumb' ENTER key press. error [error] Element name=code not ...

Rebooting Vue.js within the function

Snippet of code for showing an input field and focusing on it when mouseover occurs: Template: <span @mouseover="hoverOn('givenName')"> <input v-show="this.hovers['givenName']" ref="givenName" v-model="... and method ...

What is the best way to loop through a JSON property without knowing if it is an array or not?

I'm facing a challenge with an API response where the DEPARTURESEGMENT can sometimes contain only one object and other times it contains an array of objects. This variation requires different logic in my foreach-loop. Response A: { "getdeparturesr ...

Center text in the v-text-field label

Greetings! I've attempted various methods to center the label in my v-text-field, but unfortunately none of them have been successful. Please see the code snippet below: HTML Code <v-text-field dark class="centered-input" label="your code">< ...

display the array of arrays as an image using React

Just starting out with react js and I'm working with some data that looks like this: The 'data' variable is an array containing elements, one of which is data[22] with the following structure: data[22] elements. images [4]: 1 ...

Encountering an issue with Spring and AngularJS, as I am receiving an HTTP Status 404 error message

I'm encountering an HTTP Status 404 error within my controller. Server code @RequestMapping(value="/showMsg/", method=RequestMethod.GET,produces= { "application/json" })' public ResponseBody String show(){ HashMap hash = new HashMap(); ...