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

Issue with Bootstrap v3.3.6 Dropdown Functionality

previewCan someone help me figure out why my Bootstrap dropdown menu is not working correctly? I recently downloaded Bootstrap to create a custom design, and while the carousel is functioning properly, when I click on the dropdown button, the dropdown-menu ...

Utilize Jquery to hide radio buttons, while allowing users to click on an image to display a larger version

My current HTML structure is restricted to SAAS, so I only have control over jQuery implementation. https://i.stack.imgur.com/OHB9K.jpg I am attempting to achieve a similar layout as shown in the image below. The main issue lies in how to (1) conceal ...

Having trouble interpreting sub items with JSON parsing

I'm encountering an issue with parsing and formatting my JSON data correctly. Can anyone provide guidance on how to parse the data accurately in this particular scenario? SOURCE: try { HttpURLConnection conn = (HttpURLConnection) new U ...

Launching a Node.js Express application on Heroku

I'm facing an issue while trying to deploy my app on Heroku, as I keep encountering the following error: 2022-08-11T12:49:12.131468+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306 2022-08-11T12:49:12.131469+00:00 app[web.1]: at TCPConnect ...

limit mongoose search results to a specific year

Would it be possible to add an option for the api user to filter the wine query by year? However, if no year is specified, mongoose should not return an empty array. The same applies to the price property. For example, http://localhost:1234/api/wine?year= ...

Looking to send an HTTP request to submit a form within a Node.js application to an external website?

Can someone help me with submitting a form on a different site and receiving a response? I'm having trouble figuring out how to do this. Here is the website I am targeting: Below is my code snippet: var http = require('http'); var options ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Obtaining the source code in CKEditor while in edit mode with Rails

As a Rails developer, I recently utilized CKEditor in one of my applications. After writing a sample HTML source code in the editor and submitting it, the code displayed properly on the front-end as a GUI. However, when attempting to edit the source code f ...

ExpressJS looping back

After exploring and practicing the creation of Rest APIs with both Loopback and ExpressJS individually, When using Loopback: I found it to be quite time-consuming to go through all the documentation and learn about loopback-specific features. However, i ...

Incorporate relationships while inserting data using Sequelize

vegetable.js ... var Vegetable = sequelize.define('Vegetable', { recipeId: { allowNull: false, ... }, name: { ... }, }); Vegetable.association = models => { Vegetable.belongsTo(models.Recipe); }; ... recipe.js ... var Recipe = sequeliz ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

Retrieve a collection of CSS classes from a StyleSheet by utilizing javascript/jQuery

Similar Question: Is there a way to determine if a CSS class exists using Javascript? I'm wondering if it's possible to check for the presence of a class called 'some-class-name' in CSS. For instance, consider this CSS snippet: & ...

JavaScript special character encoding techniques

I'm trying to create a function to remove special characters in my JavaScript code. However, whenever I try using chr(46), it throws a syntax error. Does anyone have any suggestions on how I can successfully implement chr(46) in my JS code? storageV ...

How can we format a number to match the Brazilian number system while still maintaining its ability to be used in calculations?

Is there a known method to convert the number 123,123,214.93 into Brazilian currency format (123.123.214,93) for display purposes only? I attempted to achieve this conversion using a JavaScript function where I added periods after every 3 numbers and repl ...

JS, Async (library), Express. Issue with response() function not functioning properly within an async context

After completing some asynchronous operations using Async.waterfall([], cb), I attempted to call res(). Unfortunately, it appears that the req/res objects are not accessible in that scope. Instead, I have to call them from my callback function cb. functio ...

Google Maps GeoCoding consistently relies on the language settings of the browser in use

I have implemented the Google AJAX API loader to retrieve information in German by loading the maps API using this code: google.load("maps", "2", {language : "de"}); Despite trying variations such as deu, ger, de, de_DE, and ...

Managing numerous API requests in React Native

As I work on implementing a search field, I've encountered a challenge. Whenever a user enters text in the search field, a timer resets to 300 ms before an API call is sent to fetch autocomplete results. After receiving these results, the app then wai ...

Combine both typescript and javascript files within a single Angular project

Is it feasible to include both TypeScript and JavaScript files within the same Angular project? I am working on a significant Angular project and considering migrating it to TypeScript without having to rename all files to .ts and address any resulting er ...

Select a Date: Input for Date Selection

Is it possible to restrict the selection of certain days using HTML date input validation? Some booking websites have a feature where an interactive calendar only allows users to select specific dates for events, while others are greyed out and cannot be c ...