What strategies can I use to efficiently maneuver through quiz questions?

Currently, I am immersed in a Quiz project and am looking to progress to the next question. However, I have encountered an issue with the getElementById() function:
Uncaught TypeError: Cannot set property 'innerHTML' of null :
document.getElementById("questionNum").innerHTML = "Question " + (quiz.questionIndex + 1);

<!-- my html -->
    <div id="container">

        <div id="QuestionContainer", style="display:block;">
            <h2 style="margin-left:30px" id="questionNum"></h2>

            <div id="question" style="font-size:20px; font-weight:bolder;margin-bottom:20px; margin-left:30px;">    

            </div>

            <div id="answerContainer">
                    <button value="0" id="choice0" name="answer" class="aButton" onclick="checkAnswer(this.value)">
                        <label id="label0" class="label"></label>
                    </button>

                    <button value="1" id="choice1" name="answer" class="aButton" onclick="checkAnswer(this.value)">
                        <label id="label1" class="label"></label>
                    </button>

                    <button value="2" id="choice2" name="answer" class="aButton" onclick="checkAnswer(this.value)"> 
                        <label id="label2" class="label"></label>
                    </button>

                    <button value="3" id="choice3" name="answer" class="aButton" onclick="checkAnswer(this.value)">
                        <label id="label3" class="label"></label>
                    </button>

            </div>

        </div>

        <button id="back" class="navButton"> Back </button>
        <button id="next" class="navButton"> Next </button>

    </div>

This is my js code used for checking answers and navigating through questions.

var questions = [
    new Question("HyperText Markup Language Stands For?", ["JavaScript", "XHTML","CSS", "HTML"], "HTML", 3),
    new Question("Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS", 2),
    new Question("Which is not a JavaScript Framework?", ["Python Script", "JQuery","Django", "NodeJS"], "Django", 2),
    new Question("Which is used to Connect To Database?", ["PHP", "HTML", "JS", "All"], "PHP", 0)
];

var quiz = new Quiz(questions);

function Question(question, choices, answer, keyId){
    this.question = question;
    this.choices = choices;
    this.answer = answer;
    this.keyId = keyId;
}

function Quiz(questions){
    this.questions = questions;
    this.questionIndex = 0;
    this.questionAnswered = 0;
    this.correctAnswer = 0;
    this.start = 0;
}

Quiz.prototype.isEnded = function(){
    return (this.questionAnswered === 2);
}

Quiz.prototype.getQuestion = function(){
    return (this.questions[this.questionIndex]);
}

Quiz.prototype.isNext = function(){
    var button = document.getElementById("next");
    button.onclick = function(){
        this.questionIndex++;
    }
}


function isNextQuestion(quiz){
    var button1 = document.getElementById("next");
    var button2 = document.getElementById("back");
    button1.onclick = function(){
        quiz.questionIndex++;
    }
    button2.onclick = function(){
        quiz.questionIndex--;
    }

}

function setQuestion(quiz) {
    
    if (!quiz.isEnded())
    {
        document.getElementById("questionNum").innerHTML = "Question " + (quiz.questionIndex + 1);
        document.getElementById("question").innerHTML = quiz.questions[quiz.questionIndex].question;

        document.getElementById('label0').innerHTML = quiz.questions[quiz.questionIndex].choices[0];
        document.getElementById('label1').innerHTML = quiz.questions[quiz.questionIndex].choices[1];
        document.getElementById('label2').innerHTML = quiz.questions[quiz.questionIndex].choices[2];
        document.getElementById('label3').innerHTML = quiz.questions[quiz.questionIndex].choices[3];
    }
}


function getStarted(quiz){
    setQuestion(quiz);
}

function checkAnswer(value) {
    setQuestion(quiz);
    if (parseInt(value) == quiz.getQuestion().keyId)
    {
        document.getElementById("choice" + quiz.getQuestion().keyId).style.backgroundColor = "#3BF500";
        document.getElementById("choice" + value).style.backgroundColor = "#3BF500";
        quiz.questionAnswered++;
        quiz.correctAnswer++;
        for (var i = 0; i < 4; i++)
            document.getElementById("choice" + i).disabled = true;
    }
    else
    {
        document.getElementById("choice" + quiz.getQuestion().keyId).style.backgroundColor = "#3BF500";
        document.getElementById("choice" + parseInt(value)).style.backgroundColor = "red";
        quiz.questionAnswered++;
        for (var i = 0; i < 4; i++)
            document.getElementById("choice" + i).disabled = true;
    }
}

getStarted(quiz);

Answer №1

Ensure you include an event listener for the next button in your JavaScript code

document.getElementById('nextButton').addEventListener("click", function() {
  quiz.currentQuestion++;
  displayNextQuestion(quiz);
});

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

Having trouble getting the <script> tag to function properly in HTML <head> or an external JS file

Attempting to include js in an HTML file. Imported the external js files using the script tags below <script type="text/javascript" src="scripts/ui.js"></script> <script type="text/javascript" src="scripts/events.js"></script> Unf ...

Organize data in a Vue.js table

Currently facing an issue with sorting my table in vue.js. Looking to organize the table so that campaigns with the highest spend are displayed at the top in descending order. Here is the code I'm working with: <template> <div class=" ...

ajax - Text not appearing in Google's cached version

My website retrieves content using MS AJAX from an ASP.NET webservice. However, when I check the cached version on Google, I notice that the initial text is not displayed. I am wondering what would be the most effective method to ensure the website's ...

Utilize interpolation with ES6 and an Angular 1.4 directive

Currently experimenting with the unique ES6 + Angular combination and facing a challenge in interpolating an html string within a directive that includes scope bindings. We have attempted the following approach: Current scenario The code below is functi ...

Using jQuery to trigger a Bootstrap modal when a button is clicked

I've been attempting a simple task, but it appears to be unsuccessful. I'm trying to handle the click event of a button inside a bootstrap modal, and so far, nothing happens when clicking the button. My guess is that my jQuery selector for select ...

Issue with React component not receiving dataThe values are not being

Currently, I am a beginner in using React and as part of my training, I have embarked on a project to create a simple book ranking system. In this project, the user enters the title of the book they would like to vote for. If the input field is left empty, ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

Can CSS be used to horizontally align individual characters by adjusting letter-spacing?

When I apply the CSS rule letter-spacing: 16px;, I observe that the characters are aligned to the left within their designated space, causing the cursor to jump towards the right as if an additional space was added after each character. I am wondering if ...

Exploring the depths of a nested JSON file

Seeking assistance with navigating through a nested JSON file. I am not very familiar with jQuery, so a brief explanation of how it functions would be greatly appreciated. $(window).load(function(){ $.each(data.videos, function(entryIndex, entry) { ...

difficulty with closing nested Mat-dialogBoxes

I am facing an issue with passing data between multiple dialog boxes in my parent raster component. I have a parent raster component that opens the first dialog box, followed by a second dialog box. My goal is to pass data from the last dialog box back to ...

Dealing with child elements in isomorphic React applications: a comprehensive guide

Looking at my server code, here is how it appears: var data = { scripts: scripts, children:[<Comp1 />, <Comp2 />, <Comp3 />] }; // keeping smaller for easier example than reality var markup = ''; markup += '<scrip ...

The XHR Get request fails to load the HTML content sent from the Express application

As I embark on building my inaugural express app, I have encountered a shift in sending requests from the front-end. Previously, all requests were initiated by anchor elements for GET requests and form elements for POST requests, with server responses hand ...

Is it possible to validate the data first before returning a resolve?

How can we use a Promise to resolve if all fields are valid or reject if any field is invalid? let validateData = (data) => { let fields = [ 'Field1', 'Field2', 'Field3' ]; return new P ...

Accessing JavaScript file on various endpoints

Currently, I am developing a large javascript application which functions as a single page application. My technology stack includes node.js with jade. I have some concerns regarding the loading of javascript files for the front end. Let's say we hav ...

The search bar is preventing the props from being updated

Whenever I navigate between columns on my website, the <ArticleList> is supposed to update. It works flawlessly when moving from the home page to a column, or from an article to a column. However, the issue arises when going from one column to anothe ...

Encountering an issue where I am unable to access properties of undefined (specifically 'up') within Material UI styling

I encountered an error message Uncaught TypeError: Cannot read properties of undefined (reading 'up') while executing the code snippet below: I am having trouble with compiling my react js Code Snippet from Index.js import React from 'react ...

PNG file unable to display in Google Chrome

I created an image using paint.net and saved it as a .png file. However, when I try to display the image on my website, only the borders show up without any image content. Here is the code I used: HTML <a href="home.php"><img id="logo" src="../i ...

Utilizing a for loop to add div elements

I have a HTML form in my code where the user fills out information, including entering a value in the "member" field and clicking a button to generate additional copies of the 'sector_prop' div. The form section is - Number of Sectors (L ...

The state in React's useState and useEffect seems to lag behind by one step

Understanding that updates to state are asynchronous and batched for performance reasons, I made the decision to utilize useState() and useEffect() in order to synchronize with my state before taking action. However, I encountered a problem where my state ...

fancybox guaranteeing that the fancybox image is not stored in the cache

I'm encountering a problem with fancybox where it's loading a cached image. I want to prevent the image from being cached before displaying it on the page, but so far, my attempts with various callbacks (beforeShow, afterShow, afterLoad, beforeLo ...