My JavaScript code seems to be malfunctioning as the content from my two-question form is not appearing within the central div. Is there anyone available who can help troubleshoot and correct my JavaScript

Can someone help correct my JavaScript code and explain the necessary steps taken to do so? I'm trying to figure out what mistake caused my quiz questions and options to not display correctly within the central div.

Giving some background on my code: it's a two-question form, where the results should appear at the top of the page after clicking the Evaluate button. However, my current focus is on making sure the quiz is visible on the HTML/CSS page.

Link to CodePen: Check out my code here

const quizQuestions = {
    questions = {
      question: "What is the capital city of Pará?",
      alternatives: {
        0: "São Paulo",
        1: "Guarulhos",
        2: "Campinas",
        3: "São Bernardo do Campo",
        4: "São José dos Campos",
        5: "Santo André",
        6: "Ribeirão Preto",
        7: "Belém",
        answer: "7"
      },

      {
        question: "Which city is the capital of Amapá state?",
        alternatives: {
          0: "Osasco",
          1: "Sorocaba",
          2: "Mauá",
          3: "Macapá",
          4 "São José do Rio Preto",
          5: "Mogi das Cruzes",
          6: "Santos",
          answer: "3"
        };

        document.getElementByClassName('.quiz-container ').addEventListener('click', function() {

          let container =
            document.querySelector('.quiz-container');
          container.innerHTML = '<div class="quiz-container"></div>';
          for (const [key, value] of Object.entries(quizQuestion.alternatives)) {
            container.innerHTML += `<input type="radio" name="choice" value="${key}"> ${value}`;
          }
          container.innerHTML += '<div><button type="submit" id="submit-button">Evaluate</button></div>';



          document.getElementById('submit2').addEventListener('click', function(event) {
            console.log('asdf');
            event.preventDefault();
            var selected = document.querySelector('input[type="radio"]:checked');
            if (selected && selected.value == quizQuestion.answer) {
              alert('Correct answer!');
            } else {
              alert('Incorrect answer :(');
            }
          });
        });
body {
  background: rgb(209, 29, 83);
  margin: 0;
}

h1 {
  background: rgb(255, 184, 201);
  height: 60px;
  margin: 0;
  padding-left: 20px;
  padding-top: 20px;
  font-size: 45px;
  text-shadow: 3px 3px 9px;
  color: rgb(43, 29, 14);
}

.quiz-container {
  text-align: left;
  font-size: 25px;
  background: rgb(255, 209, 220);
  width: 700px;
  height: 4000px;
  margin: auto;
  margin-top: 100px;
  box-shadow: 9px 9px 10px;
  margin-bottom: 60px;
}

button {
  margin-left: 900px;
  padding-top: 0;
  margin-bottom: 60px;
}

.questions {
  color: #000000;
  text-align: center;
  font-size: 15px;
}
<head>
  <h1>Brazilian Quiz Centered Theme</h1>
</head>

<body>
  <div class="quiz-container"></div>

  <div>
    <button type="submit" id="submit-button">Evaluate</button>
  </div>

  <script src="js/main.js"></script>
</body>

Answer №1

There seems to be several issues within your code.

To begin with, the structure of your quizQuestions is incorrect. It should be an array consisting of objects, each containing a question, an array of alternatives, and the correct answer - I have made the necessary corrections in the provided snippet.

Another issue arises from how you are attempting to target elements using classes. Keep in mind that classes are not unique like ids, so when selecting elements, avoid using classes for unique identification purposes. Additionally, I noticed some errors in your usage of methods like document.getElementByClassName, which should actually be document.getElementsByClassName. Furthermore, using a period ('.') as a selector is more suited for CSS or jQuery, but it's not appropriate for element selection. I have updated this part to use ids instead, aligning with best practices.

While there may have been some confusion on your end regarding certain aspects of the implementation, the adjustments made should provide a solid foundation for further progress. Note that I excluded the section responsible for checking answers, focusing primarily on fulfilling your request to populate the container with questions.

const quizQuestions = [{
  question: "What is the capital of the state of Pará?",
  alternatives: [
    "São Paulo",  
    "Guarulhos",
    "Campinas", 
    "São Bernardo do Campo", 
    "São José dos Campos", 
    "Santo André", 
    "Ribeirão Preto", 
    "Belém"
  ],
  answer:7
},{
  question: "What is the capital of the state of Amapá?",
  alternatives: [
    "Osasco", 
    "Sorocaba", 
    "Mauá", 
    "Macapá", 
    "São José do Rio Preto",
    "Mogi das Cruzes", 
    "Santos"
  ], 
  answer:3
}];

window.onload = function (){
  const container = document.getElementById('quiz-container');
  quizQuestions.forEach((question, number) => {
    let questionHTML = `<div class="question"><h3>${question.question}</h3>`;
    question.alternatives.forEach((value, key) => {
      questionHTML += `<input type="radio" name="${number}choice" value="${key}">${value}<br />`;
    });
    questionHTML += "</div>";
    container.innerHTML += questionHTML;
  });
};
body {
  background: rgb(209, 29, 83);
  margin: 0;
}

h1 {
  background: rgb(255, 184, 201);
  height: 60px;
  margin: 0;
  padding-left: 20px;
  padding-top: 20px;
  font-size: 45px;
  text-shadow: 3px 3px 9px;
  color: rgb(43, 29, 14);
}

#quiz-container {
  text-align: left;
  font-size: 25px;
  background: rgb(255, 209, 220);
  width: 700px;
  height: 4000px;
  margin: auto;
  margin-top: 100px;
  box-shadow: 9px 9px 10px;
  margin-bottom: 60px;
}

button {
  margin-left: 900px;
  padding-top: 0;
  margin-bottom: 60px;
}

.question {
  color: #000000;
  text-align: center;
  font-size: 15px;
}
<head>
  <h1>QUIZ centred in Brazil</h1>
</head>

<body>
  <div id="quiz-container"></div>

  <div>
    <button type="submit" id="submit-button">Evaluate</button>
  </div>

  <script src="js/main.js"></script>
</body>

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

I am having an issue with the <a> element in my bootstrap carousel, as it is displaying a dead link

My carousel has an issue with the anchor tag, causing it to show a dead link. I am unable to hover over it and the link is not functioning when clicked. Everything else seems to be working fine in the div. All files from Bootstrap have been used and no cha ...

Is it possible for Node.js to execute individual database operations within a single function atomically?

As I delve into writing database queries that operate on node js, a puzzling thought has been lingering in my mind. There seems to be a misunderstanding causing confusion. If node is operating in a single-threaded capacity, then it follows that all functi ...

The nonexistence of the ID is paradoxical, even though it is present

I've been working on a school project that involves a dropdown box with the id "idSelect." However, I'm encountering an issue where it says that idSelect is not defined when I try to assign the value of the dropdown box to a variable. Even after ...

Utilizing Mongoose aggregation for counting and grouping operations

I am trying to search for records that correspond to a specific URL but want to return a customized object instead. Here is the model I am working with: const ReactionSchema = mongoose.Schema({ url: { type: String, required: true }, emoji: ...

Using jQuery to append content with a variable as the source

Recently delving into jQuery and encountering an issue with getting my variable inside src when using append. Either it's not functional at all, or just displaying the variable name in string form in the console. Here is the code causing trouble: va ...

How about displaying the Ajax response as an image?

I'm working on a script that pulls an image link, which seems to be functioning correctly. However, I am struggling with how to display the link as an image. Can someone please assist me with this? <script src="//ajax.googleapis.com/ajax/li ...

The Colorbox feature showcases images in their binary data format

I'm currently experimenting with using Colorbox to enhance a website that is being built with Backbone.js. Within my code, I have a straightforward image tag set up like this: <a class="gallery" href="/document/123"><img class="attachment-pr ...

Exploring Particles with three.js

Could you please help me understand why there are no particles visible in this code snippet? I followed a tutorial and it all seems correct. (function() { var camera, scene, renderer; init(); animate(); function init() { scene = new THREE.Scene(); ...

Tips for vertically centering a span within a div that is floated to the right

Need help centering a span vertically within a div when using float:right? <div class="card"> <div class="card-header"> <h5>TEST</h5> <span class="fa fa-info"></span> </div> <div class="card-body" ...

Organizing a Collection of Likes within an AngularJS Service

I have a like button on my profile page that, when clicked, should add the user's like to an array and store it in the database. Within my profile controller, I have the following code: $scope.likeProfile = UserService.likeProfile(loggedInUser,$stat ...

The React Reducer is yielding an undefined result

I am facing an issue with a particular property, disableselectors, which is currently returning undefined in my mapStateToProps(state). return { token: state.token, url: state.url, disableselectors: state.disableselectors } Here is the reduce ...

Error: Whereabouts of Angular PHP file remains elusive

I need to collect a date and transfer it to the php file. $http.post('views/php.php', { item: $scope.email }) .success(function(data) { console.log(data); }); However, the console log displays the following: POST http://localhost:9000/vi ...

Choosing an option in Vue using select, v-for loop, and v-model

How can I set a preselected option in a select element using v-model, v-for for options, and an object as the value? The options are elements with unique ids, and I want to preselect based on custom equality (e.g., matching the id field). Is there a way to ...

Using jQuery to modify a CSS property when a specific option is chosen

I'm currently working on creating an option dropdown menu and I've hit a roadblock trying to display a textbox only when the 'other' option is selected. Here's what I have so far: <span id="con-country"><label for="count ...

Learn how to toggle the visibility of a "Tr" element by clicking on a radio button list

I am looking to implement a functionality where I have two "tr" elements: First "tr" contains a file upload control. Second "tr" contains a text box control. In addition, there is a radio button list with three values: 1. Image 2. Video 3. Audio The ...

Passing onClick event to parent component during iteration in ReactJS

I am facing a challenge where I need to remove a row from a table upon a click event. I have managed to create an iteration and display a delete button, but I am struggling with passing the onClick event from the parent component to the child component in ...

I'm having trouble getting my innerHTML command to update anything on the webpage, and the reason is eluding me

Below is the code snippet provided: <div id="js"><button onclick="document.getElementById('js').innerHTML=('<form> <input type=text name=tick1></input> <input type=text name=tick2></input> ...

Modifying the HTML Structure in Yii's CListView

I need help with modifying the HTML output of my CList view when there is pagination present. Currently, it displays: Showing 1-3 out of 5 items. However, I want to remove this message from the top of the pagination. Can someone guide me on how to achie ...

Save the user input to a dedicated text file

I am working with a couple of select tags that generate an array. Previously, I was only logging the array to the console upon pressing the SUBMIT button, but now I want to save it to a separate text file. Here is my main.html code: <form method="POS ...

Resolving problems with the positioning of the navigation bar

I am in the process of creating a simple website, but I am encountering an issue with the menu bar shifting below the "Contact for Services" section when I view the page in different resolutions. Is there a way to lock the position of the menu bar so that ...