In Javascript, assign default values to an array and update them with new values upon the click of a

My goal is to create a quiz that populates an array. Initially, the quiz is empty but I aim to assign it a default value.

This serves as my question navigation:

        /**
         *
         * @param {int} question
         * @returns {QuizPart}
         */
        SetQuestion(question) {

            if (this.questionNumber >= 0) {
                let oldAnswerButton = document.querySelectorAll('.filter_anwser');

                // Removes previous question when a new one is selected
                for (let answerButton of oldAnswerButton) {
                    answerButton.style.display = 'none';
                }
            }

            this.questionNumber = question;

            let q = this.quiz[question];
            // Checks if it's the last question to adjust button display
            if (this.questionNumber === Quiz.length - 1) {
                this.nextbtn.style.display = 'none';
                this.prevbtn.style.display = 'block';
                this.resultbtn.style.display = 'grid';
            } else if (this.questionNumber === 0) {
                this.nextbtn.style.display = 'block';
                this.prevbtn.style.display = 'none';
                this.resultbtn.style.display = 'none';
            } else {
                this.nextbtn.style.display = 'block;
                this.prevbtn.style.display = 'block;
                this.resultbtn.style.display = 'none';
            }

            // Shows Question
            this.questionName.textContent = q.questionText;
            this.questionName.id = "questionID";

            return q;
            console.log(this.getLink())
            console.log(this.tmp)

        }

        IntoArray() {
            const UrlVar = new URLSearchParams(this.getLink())
            this.UrlArray = [...UrlVar.entries()].map(([key, values]) => (
                    {[key]: values.split(",")}
                )
            );
        }

        NextQuestion() {
            let question = this.SetQuestion(this.questionNumber + 1);
            let pre = question.prefix;
            let prefixEqual = pre.replace('=', '');
            let UrlArr = this.UrlArray;
            let UrlKeys = UrlArr.flatMap(Object.keys)
            let answers = question.chosenAnswer.slice(0, -1);

            // Displays answers of the questions
            for (let y = 0; y < answers.length; y++) {
                let item = answers[y];

                // Display answer buttons
                if (UrlKeys.includes(prefixEqual)) {
                    console.log("exists");
                    let btn = document.querySelector('button[value="' + item.id + '"]');
                    btn.style.display = 'block';
                } else {
                    let btn = document.createElement('button');
                    btn.value = item.id;
                    btn.classList.add("filter_anwser", pre)
                    btn.id = 'answerbtn';
                    btn.textContent = item.name;
                    this.button.appendChild(btn);
                }
            }
            this.IntoArray();
        }

        PrevQuestion() {
            let question = this.SetQuestion(this.questionNumber - 1);
            let answers = question.chosenAnswer.slice(0, -1);

            // Displays answers of the questions
            for (let y = 0; y < answers.length; y++) {
                let item = answers[y];

                // Display answer buttons
                let btn = document.querySelector('button[value="' + item.id + '"]');
                btn.style.display = 'block';
            }
            this.IntoArray();
        }

Link builder and eventlistener:

        getLink() {
            this.tmp = [];
            for (let i = 0; i < this.url.length; i++) {
                // Check if question is from the same quiz part and add a comma between chosen answers and add the correct prefix at the beginning
                if (this.url[i].length > 0) {
                    this.tmp.push("" + Quiz[i].prefix + this.url[i].join(","))
                    // console.log(this.url)
                }
                    if (this.url[i].length === 0) {
                        this.tmp.push("");
                }
            }
            /// If answers are from different quiz parts add an ampersand between answers.
            return "" + this.tmp.join("&");
            // console.log(this.url[i].prefix);
        };

    control.button.addEventListener("click", function (e) {
        const tgt = e.target;

        // clear the url array if there's nothing clicked
        if (control.url.length === control.questionNumber) {
            control.url.push([]);
        }

        let quizUrl = control.url[control.questionNumber];

        // Check if a button is clicked. Changes color and adds value to the url array.
        if (quizUrl.indexOf(tgt.value) === -1) {
            if(quizUrl.includes("")){
                quizUrl.splice(quizUrl.indexOf(tgt.value), 1);
            }
            quizUrl.push(tgt.value);
            e.target.style.backgroundColor = "orange";
            // Check if a button is clicked again. If clicked again changes color back and deletes value in the url array.
        } else {
            quizUrl.splice(quizUrl.indexOf(tgt.value), 1);
            e.target.style.backgroundColor = "white";
        }

        console.log(control.getLink());
        console.log(quizUrl)

    })

When pressing a button, I add a value from an array to a separate array called url. The constructor definition looks like this:

this.url = ["","",""];

The array has three strings representing each question with a default value set. In the event listener, I implement an if statement to check for an empty string in the url and splice it out. However, I encounter an error message stating:

(index):329 Uncaught TypeError: quizUrl.splice is not a function at HTMLDivElement. ((index):329:25) (anonymous) @ (index):329

I require a default value so that I can skip answering all questions while still being able to proceed with the quiz. Can anyone suggest a solution to resolve this issue?

Answer №1

To enhance your Quiz, consider inserting the following snippet:

this.links = [];
for (let i = 0; i < quiz.length; i++){
    this.links.push([]);
}

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

Utilizing Javascript for altering HTML elements

It seems this issue is quite puzzling and I believe another perspective could be beneficial in identifying the problem. Despite my efforts, I am unable to understand why the "Energy Calculator" does not return a value when submitted, whereas the "Battery C ...

What is the best way to post an image using nodejs and express?

Recently, I've been working on a CMS for a food automation system and one feature I want to incorporate is the ability to upload pictures of different foods: <form method="post" enctype="multipart/form-data" action="/upload"> <td>< ...

Python code to transform an integer array into a binary array

I'm attempting to convert an array of integers into binary format using Python 2.7. Here's a simplified version of the code I'm working with: #!/usr/bin/python import numpy as np a = np.array([6, 1, 5, 0, 2]) b = np.zeros((5)) for i i ...

The request.files property in express-fileupload is consistently coming back as undefined

I am trying to achieve the task of uploading a file from my browser and sending it via POST to an Express.js application, which will then download the file using express-fileupload. Here is the client-side JavaScript code I have written so far: // Triggere ...

Retrieving data from a parent object within an iframe on a different origin

In order to incorporate a feature on various websites, I am looking to embed an iframe with JavaScript. This iframe should have the ability to interact with the parent object and display or hide certain elements on the webpage. The main HTML file includes ...

Merging two arrays to create a JSON object

column_names: [ "School Year Ending", "Total Students", "American Indian/Alaskan Native: Total", "American Indian/Alaskan Native: Male", "American Indian/Alaskan Native: Female", "Asian/Pacific Islander: Total", "Asian/Pacific I ...

What is the process for configuring a registry for a namespaced package using yarn?

Experimenting with yarn as a substitute for npm has been quite interesting. With npm, we usually rely on both a private sinopia registry and the official repository for some namespaced packages, since sinopia doesn't support namespaces. My .npmrc fi ...

Getting the input tag id of an HTML form can be achieved by using the "id

<?php $i = 1; $query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page.""); while($result = mysql_fetch_array($query1)){ echo '<td colspan = "2">& ...

Initiate the countdown when the button is pushed

Recently ran into an issue where a button triggers a command to a Perl script, causing the page to continuously load for 60 seconds. To provide users with transparency on when the Perl script will be finished running, I implemented a JavaScript countdown t ...

"Can you provide some guidance on transferring the selected row value to a button that is located outside the grid, including a parameter in v-data-table

<v-toolbar flat> <v-toolbar-title>Details</v-toolbar-title> <div style="width:100%"> <v-col class="text-right"> <v-btn id="btnCopy" @click="Redirect()" clas ...

Material Design Forms in Angular: A Winning Combination

I'm currently working on developing a form using Angular Material. This form allows the user to update their personal information through input fields. I am utilizing "mat-form-field" components for this purpose. However, there are certain fields tha ...

Node React authentication

Struggling with implementing authentication in React Router. I am using componentDidMount to check if the user is logged in by calling an endpoint. If not, it should redirect to login, otherwise proceed to the desired component. However, this setup doesn&a ...

React form input values fail to refresh upon submission

After attempting to upload the form using React, I noticed that the states are not updating properly. They seem to update momentarily before reverting back to their original values. I am unsure of why this is happening. Take a look at this gif demonstrati ...

Converting JSON data into objects in JavaScript

My task involves processing a large JSON list with over 2500 entries, formatted as follows: [ ['fb.com', 'http://facebook.com/'], ['ggle.com', 'http://google.com/'] ] This JSON list represents pairs of [&ap ...

Angular 4 applications do not come with TinyMCE embedded

I've been attempting to integrate the tinyMCE editor into an angular4 application, but unfortunately I encountered an error that reads: tinyMCE is not defined. https://i.stack.imgur.com/qMb5K.png I have been following the guidance provided by tin ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

Delivering Background Videos with Node.JS

Apologies if my question seems off base or confusing, as I am not very knowledgeable in the world of nodejs. I have been comfortable using just plain PHP and Apache for a while until I discovered ZURB Foundation's stack with Handlebars and SASS, along ...

Exploring VueJS Router History Mode with NGinx web server

After conducting research, I discovered several issues similar to the one I am facing. Currently, I have a docker-compose setup on Digital Ocean with NGinx, VueJS, and a Static Landing Page. Everything was working fine until I added a new route with a fo ...

Generating a JSON Array by aggregating data from a loop with the help of the Spring Boot framework

Recently, I successfully implemented a code to import data from a .pcap file. The code works flawlessly as it reads the cap files and displays the results in the console. The implementation of this code can be seen below: @SpringBootApplication public cl ...

"The NextJS FetchError that occurred was due to a timeout issue (ET

After successfully deploying my project on CentOS 7, I set up port forwarding to access it through port 8080. This means that in order to use the site, you had to navigate to it using the IP followed by :8080. Below is the NGINX configuration I utilized fo ...