I am experiencing an issue with the initial for-loop in my code as it is not

Upon clicking the start button, the score button, as well as the try again or correct button, are not being updated. Can someone help me figure out what's wrong?

I believe the issue lies within this section of the code:

for (i=0; i<5; i++) {
  document.getElementById("Box"+i).onclick= function() {
    if (playing == true) {
      if (document.getElementById("Box"+i).innerHTML == correctAnswer) {
        score ++ ;
        document.getElementById("ScoreValue").innerHTML = score;
        hide("Wrong");
        show("Correct");
        setTimeout(function() {
          hide("Correct");
        }, 1000)
        generateQA() // Generate new Q/A
      } else { // Wrong answer
        hide("Correct");
        show("Wrong");
        setTimeout(function() {
          hide("Wrong");
        }, 1000)
      }
    }
  }
}

Answer №1

After reviewing your code, I identified a few minor issues that I was able to address while ensuring minimal changes.

I made sure to maintain the core functionality without altering it significantly.

var playing = false;
var action;
var score;
var timeremaining;
var correctAnswer

const boxes = document.querySelectorAll(".Box")

document.getElementById("Startreset").onclick = //if we click on start/reset
  function() {
    if (playing == true) //if we are playing
    {
      location.reload();
    } else //if we are not playing
    {
      playing = true; //change mode to playing
      score = 0; //set score to  0
      document.getElementById("ScoreValue").innerHTML = score;

      show("Timeremaining"); //show countdownbox
      timeremaining = 60
      document.getElementById("Timeremainingvalue").innerHTML = timeremaining;

      document.getElementById("Startreset").innerHTML = "Resetgame"; //Reset the game
      startCountdown();
      //generate a new question
      generateQA();

    }
  }
// clicking on answer button
for (i = 1; i < 5; i++) {
  document.getElementById("Box" + i).onclick = function(e) {
    if (playing == true)

    {
      const answer = e.target.innerHTML;
      console.log('My answer is', answer, correctAnswer)
      if (this.innerHTML == correctAnswer) {
        score++;
        document.getElementById("ScoreValue").innerHTML = score;
        hide("Wrong");
        show("Correct");
        setTimeout(function() {
          hide("Correct");
        }, 1000)
        generateQA() //genrate new Q/A
      } else { //wrong answer

        hide("Correct");
        show("Wrong");
        setTimeout(function() {
          hide("Wrong");
        }, 1000)

      }
    }

  }
}



function startCountdown() { //start counter
  action = setInterval(function() {
    timeremaining -= 1;
    document.getElementById("Timeremainingvalue").innerHTML = timeremaining;
    if (timeremaining == 0) {
      stopCountdown() //game over
      hide("Timeremaining");
      hide("Wrong");
      hide("Correct");
      playing = false;
      document.getElementById("Startreset").innerHTML = "Start Game";
    }
  }, 1000);
}
//stop counter
function stopCountdown() {
  clearInterval(action);
}
//hide an element
function hide(Id) {
  document.getElementById(Id).style.display = "none";
}
// show an element
function show(Id) {
  document.getElementById(Id).style.display = "block";
}

function generateQA() { //genrate function

  var x = 1 + Math.round(9 * Math.random());
  var y = 1 + Math.round(9 * Math.random());
  correctAnswer = x * y;
  document.getElementById("Question").innerHTML = x + "X" + y;

  var correctPosition = Math.ceil(4 * Math.random())
  //fill one box with correctanswer
  document.getElementById("Box" + correctPosition).innerHTML = correctAnswer

  //fill other boxes with wrong answer

  var answers = [correctAnswer];
  for (i = 1; i < 5; i++) {
    if (i != correctPosition) {
      var wrongAnswer;
      do {
        wrongAnswer = (1 + Math.round(9 * Math.random())) * (1 + Math.round(9 * Math.random()))
      } while (answers.indexOf(wrongAnswer) > -1) // a wrong answer
      document.getElementById("Box" + i).innerHTML = wrongAnswer;
      answers.push(wrongAnswer);
    }
  }
}
html {
  height: 100%;
  background-color: grey;
}

.Container {
  height: 500px;
  width: 1200px;
  background-color: #7fffd4;
  margin: 100px auto;
  padding: 15px;
  border-radius: 15px;
  box-shadow: 6px 6px;
}

#Score {
  background-color: rgb(203, 189, 216);
  color: white;
  position: absolute;
  left: 1275px;
  padding: 7px 8px;
  border-radius: 4px;
  box-shadow: 2px;
}

#Correct {
  position: absolute;
  background-color: green;
  left: 675px;
  color: antiquewhite;
  padding: 7px 8px;
  border-radius: 4px;
  display: none;
}

#Wrong {
  position: absolute;
  background-color: rgb(128, 119, 0);
  left: 500px;
  color: antiquewhite;
  padding: 7px 8px;
  border-radius: 4px;
  display: none;
}

#Question {
  background-color: rgb(45, 135, 204);
  height: 150px;
  width: 500px;
  color: antiquewhite;
  margin: 50px auto 10px auto;
  box-shadow: 0px 4px rgb(176, 181, 181);
  font-size: 100px;
  text-align: center;
  font-family: Arial;
}

#Instruction {
  background-color: rgb(174, 124, 207);
  margin: 10px auto;
  height: 50px;
  width: 500px;
  color: antiquewhite;
  box-shadow: 0px 4px rgb(160, 163, 173);
  text-align: center;
  line-height: 45px;
  font-family: Arial;
}

#Choices {
  height: 100px;
  width: 500px;
  margin: 5px auto;
}

.Box {
  background-color: antiquewhite;
  color: black;
  font-size: 65px;
  text-align: center;
  height: 85px;
  width: 85px;
  float: left;
  margin-right: 53px;
  position: relative;
  cursor: pointer;
  transition: all 0.2s;
}

.Box :hover #Startreset:hover {
  background-color: cadetblue;
  color: white;
  box-shadow: 0px 4px cyan;
}

#Box4 {
  margin-right: 0px;
}

#Startreset {
  width: 73px;
  background-color: rgb(232, 171, 219);
  color: black;
  position: relative;
  margin: 0 auto;
  padding: 7px 8px;
  border-radius: 4px;
  box-shadow: 2px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
}

#Timeremaining {
  width: 150px;
  background-color: rgba(13, 234, 13, 0.9);
  color: black;
  position: absolute;
  top: 488px;
  left: 830px;
  margin: 0 auto;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 2px;
  text-align: center;
  cursor: pointer;
  /* visibility: hidden;*/
  display: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>MathsTableGame t</title>
</head>

<body>

  <div class="Container">
    <div id="Score">score :<span id="ScoreValue"> 0</span></div>
    <div id="Correct"> Correct</div>
    <div id="Wrong"> Try Again </div>
    <div id="Question"> </div>
    <div id="Instruction">Click on the correct answer </div>

    <div id="Choices">
      <div id="Box1" class="Box"></div>
      <div id="Box2" class="Box"></div>
      <div id="Box3" class="Box"></div>
      <div id="Box4" class="Box"></div>
    </div>

    <div id="Startreset"> Start Game</div>
    <div id="Timeremaining">Time remaining :<span id="Timeremainingvalue">60sec</span> </div>
  </div>

</body>

</html>

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

Incorporating Bootstrap into a fresh project

I'm completely new to the world of development, so I'll do my best to phrase this question correctly! Last month, I successfully created my first web application using RoR and Bootstrap for some visual enhancements. Currently, I am working on a ...

Having trouble integrating a custom plugin with CKEditor?

I am currently using version 4.7 of CKEditor, which is the latest version available. I am facing an issue where I cannot see a new custom plugin that I have added to the toolbar. I have checked my basic example of abbreviation (abbr) plugin but couldn&apos ...

Form fields will not automatically populate with link parameters; the user must manually input the information

My form fetches data from the database using server-side code when the user inputs the "user_id" field. The User ID field is the primary field on the form, and when the user enters their user ID, all other fields retrieve the corresponding user data from t ...

Issues with aligning div elements centrally

I have a dilemma with aligning two divs on my webpage. I am trying to position the second div in such a way that it is centered between the first div and the end of the page, like this: | | | | | | | | | | | | | | div1 | ...

Endless loading on NodeJS server local host

My NodeJS setup is serving files, but the page seems to be stuck loading. Here's a snippet from my index.js file: const express = require("express"); const path = require("path"); const http = require("http"); const socke ...

Guide on incorporating an Ajax spinner to a Slideshow

I am in need of assistance with creating a manual slideshow that includes an ajax loader image. The goal is to display the loader image every time I click on the Previous or Next buttons, until the Test 1, Test 2, and Test 3 texts are fully loaded. Any sug ...

Converting HTML to PDF on iOS devices

I've encountered a challenge with a large HTML file that contains dynamically changing data. My goal is to convert this HTML document into a PDF format and send it as an email attachment. Can anyone offer advice on how I can accomplish this task? ...

Guide on converting arrays and sending this information in Node.js

I managed to retrieve quiz data and now I want to enhance it by mapping each answer to its respective quiz. I have a feeling that I should use something like forEach.push, but I haven't quite figured out the exact method... const API_KEY="https: ...

What is the best way to access a promise's value in global scope within a reactjs application?

Currently tackling user authentication using web tokens in react. My approach involves utilizing the fetch() method to send a POST request to my backend, facilitating CORS. The issue arises when attempting to employ the setToken() hook within the .then() b ...

Dealing with numerous promises simultaneously using AngularJS Factory

I have created a code that makes multiple $http calls recursively and saves all the promises it returns in an array. Then, I resolve all of them and save the responses in another array. Now, my question is: How can I efficiently return this final array to ...

locate and interact with a dynamically created button using JavaScript through ajax

Hey there, I'm trying to display an image along with a button using AJAX whenever a visitor uploads an image. for (var i = 0; i < data.length; i = i + 1) { imageThump += '<img src="' + data[i].path + '" />'; image ...

Is a CSS-only autoexpanding label possible within a list?

I am interested in having all the labels automatically expand to the size of the widest one. Below is the HTML structure: <div class="body"> <ul class="list"> <li> <span> <label>condition</label> ...

Observing the CSS class of an input element during async validation does not yield the desired results

Recently, I implemented a bootstrap directive that monitors all the input elements on a form and updates the CSS of its parent div to display validation errors in a Bootstrap-friendly manner. The directive checks for the presence of the ng-invalid class in ...

Having trouble with CSS :before pseudo-element and sibling selector?

Looking for a CSS solution to change the appearance of a triangle when the .hide class is activated within my markup. I attempted using a pseudo-element like so: summary:before { content: '\25BC'; } summary:before + .hide { con ...

clicking on a DIV element

I am trying to trigger a JavaScript function by clicking on a DIV element, but for some reason it is not working as expected. I have gone through various examples provided by the helpful people here, but still can't figure out what I'm doing wron ...

Transformation of JSON data from Array to Object

I have a JSON data structure that looks like this: { tag: 'new-tag', stream_subjects: [1, 2, 3] } My goal is to transform it into the following format: { tag: 'new-tag', stream_subjects: [ {subject_id: 1}, {subject_id ...

Exploring the possibilities of utilizing JavaScript within TypeScript

My dynamic javascript object holds all the resources (translation strings) for my app. Here's how it is structured: var ResourceManager = (function () { function ResourceManager() { var currentLanguage = $('#activeLanguage').htm ...

The Express router is failing to recognize the mongoose model

Currently, I am developing a node.js application and encountering an issue where I receive a reference error stating that Post is not defined every time I run this specific code. Interestingly, when I move the post route from submit.js to app.js, the code ...

I'm having trouble with using setInterval() or the increment operator (i+=) while drawing on a canvas in Javascript. Can anyone help me out? I'm new

I am looking to create an animation where a square's stroke is drawn starting from the clicked position on a canvas. Currently, I am facing an issue where the values of variables p & q are not updating as expected when drawing the square at the click ...

Integrate JavaScript code with HTML pages

After creating a basic HTML structure that I am proud of, I encountered some challenges with getting the Javascript to function properly. I am new to working with Javascript and received some initial assistance, but unfortunately, it is no longer working. ...