I'm struggling with my project called "Number TSP" and I can't seem to figure out why it's not working properly

Upon reaching the end of my code, I am encountering an issue where instead of seeing the expected output of "Done!", it displays undefined.

This is the code in question:

const container = document.querySelector(".container")
const table = document.querySelector('table')
const numbers = []
var chosenNum
var chosenLength;

initialize()

function initialize() {
    userChoice()
}

function playGame() {
    var counter = 0
    if (counter === cells.length) {
        console.log('Done!')
    } else {
        const cells = document.querySelectorAll('td')
        chosenNum = drawNum()
        console.log(`The selected number is ${chosenNum}! Tap it!`)
        // cells[idxOfEl].style.backgroundColor = 'yellow'
        const idxOfCell = numbers.indexOf(chosenNum)
        if (cells[idxOfCell].style.backgroundColor === 'red') {
            counter++
        }
        numbers.splice(idxOfCell, 1)
    }
}

function cellClicked(cell) {
    const numInsideCell = parseInt(cell.innerText)
    if (numInsideCell === chosenNum) {
        console.log('Awesome!')
        cell.style.backgroundColor = 'red';
        playGame();
    } else {
        console.log('You tapped the wrong number.')
    }
}


function drawNum() {
    const idxOfEl = Math.floor(Math.random() * (numbers.length))
    return numbers[idxOfEl]
}

// More functions and logic can be added here

Your feedback and suggestions for improvement are highly valuable. Feel free to share any insights you may have!

Answer №1

If you're running into issues where counter === gCells.length is being checked before initializing gCells in the playGame function, here's a solution for you. Make sure to move the declaration of gCells outside of the if statement. This will ensure that everything works correctly.

const gContainer = document.querySelector(".container")
const gTable = document.querySelector('table')
const gNumbers = []
var chosenNum
var chosenLength;


onInit()

function onInit() {
    userChoice()
}

function playGame() {
const gCells = document.querySelectorAll('td')//move this here
    var counter = 0
    if (counter === gCells.length) {
        console.log('Done!')
    } else {
        
        chosenNum = drawNum()
        console.log(`The chosen number is ${chosenNum}! Tap it!`)
        // gCells[idxOfEl].style.backgroundColor = 'yellow'
        const idxOfCell = gNumbers.indexOf(chosenNum)
        if (gCells[idxOfCell].style.backgroundColor === 'red') {
            counter++
        }
        gNumbers.splice(idxOfCell, 1)
    }
}

function cellClicked(cell) {
    const numInsideCell = parseInt(cell.innerText)
    // const timestamp = new Date().toLocaleTimeString();
    if (numInsideCell === chosenNum) {
        console.log('Awesome!')
        cell.style.backgroundColor = 'red';
        playGame();
    } else {
        console.log('You tapped the wrong number.')
    }
}


function drawNum() {
    const idxOfEl = Math.floor(Math.random() * (gNumbers.length))
    return gNumbers[idxOfEl]
}


function addNumbers(numOfCells) {
    var randNum = 0
    var counter = 0
    while (counter < numOfCells) {
        randNum = Math.floor(Math.random() * (50 - 1) + 1)
        if (!gNumbers.includes(randNum)) {
            gNumbers.push(randNum)
            counter++
        } else continue
    }
}

// ------------

function userChoice() {
    var strHTML = ''
    strHTML += `
    <h1 style="text-align:center;margin:30px">Tap the numbers!</h1>
    <p>Please choose how many cells would you like to have:</p>
    <ul>
    <li onclick="displayBoard(this)">16</li>
    <li onclick="displayBoard(this)">25</li>
    <li onclick="displayBoard(this)">36</li>
    </ul>`
    gContainer.innerHTML = strHTML
}

function displayBoard(numOfCells) {
    chosenLength = parseInt(numOfCells.innerText)
    gTable.style.display = 'table'
    var chosenLength = parseInt(numOfCells.innerText)
    addNumbers(chosenLength)
    var counter = 0
    var strHTML = ''
    strHTML += `<tbody>`
    for (var i = 0; i < Math.sqrt(chosenLength); i++) {
        strHTML += `<tr>`
        for (var j = 0; j < Math.sqrt(chosenLength); j++) {
            strHTML += `<td data-location="${i}${j}" onclick="cellClicked(this)">${gNumbers[counter]}</td>`
            counter++
        }
        strHTML += `</tr>`
    }
    strHTML += `</tbody>`
    gTable.innerHTML = strHTML
    playGame()
}
<div class="container"></div>
<table></table>

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

Avoid connecting HTML input elements with both JavaScript and Java models

I am troubleshooting an issue with my login page code. <div ng-show="!loggedIn()"> <form ng-submit="login()"> Username: <input type="text" ng-model="userName"/> Password: <input ...

Looking to create dynamic pages on NextJS without relying on fixed paths?

I am looking to create a unique user experience by offering discounts on my website based on the users' citizenship ID numbers. By using their ID number, I can customize the discount amount according to factors such as location, age, and gender. User ...

Getting started with CSS and HTML: Tips and Tricks for Beginners

Seeking advice on how to enhance my web designing skills, particularly in starting point and techniques. Currently, I am familiar with HTML and CSS, but have been primarily using pre-made templates for building websites. I aspire to be able to transform ...

The website functions properly in Chrome, but encounters issues in IE

Currently working on validating some JavaScript code. Chrome seems to be handling it well, but as expected, IE is causing some issues. Take a look at the code below: function validateData(a,id){ var inputs = document.getElementsByName('attname[] ...

Implementing customized line breaks in PHP using custom fields

My knowledge of PHP is quite limited, so I prefer to seek advice from experts before attempting anything I find online. I recently installed a customized billing field plugin in order to collect additional billing information during the checkout process. ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

What is the best way to increase the size of the input field to allow for more typing space?

My query is quite simple. Even when I set the height to 100px, the cursor still starts in the middle of the input box. I want the entire box to be utilized with the cursor starting at the top left corner for a more intuitive paragraph writing experience. ...

Error: Unable to locate module 'child_process' in the context of NextJS + Nightmare

Encountering an issue while trying to compile a basic example using Next JS + Nightmare Scraper. Upon attempting to access the page, I am faced with the following error message, and the page fails to load. PS C:\Users\lucas\Documents\Pr ...

What is the best way to retrieve the value of a property within a JavaScript object?

I am facing an issue with retrieving the value of the status property from an object in my code. Below is a snippet of what I have tried: console.log("Resource.query()"); console.log(Resource.query()); console.log("Resource.query().status"); console.log(R ...

JQuery enables nested sorting functionality

I need to enable the sortable feature specifically for the charts. Index.cshmtml <div id="sortable" class="col-lg-9"> <div class="col-lg-12 col-md-12 padding hidden" id=@($"chartNumber{Model.Charts[ ...

Problems with navigation alignment in Flask website due to HTML, CSS, and

Here's a snapshot of my current website design: website I'm attempting to place the Login & Sign up buttons in line with the rest of the navigation bar. I've tried various methods without success so far. My attempts include adjusting text a ...

Display information in a div container from other pages on the website

I am attempting to dynamically load content into a div in Index based on the selection made in a dropdown box, but it doesn't seem to be working correctly. I have created a simple example using four pages to demonstrate the issue: Index.html one.html ...

Custom Sign-in features in NextJS now direct users to the default form for entering login

I have been working on a web app that requires authentication using NextJS default auth middleware. However, whenever I try to log in, the app redirects me to the default NextJS form component at the URL /api/auth/signin?error=CredentialsSignin. Even thou ...

Error message in JavaScript saying "The response string is undefined

I am working on a program built in angularjs. Currently, I receive JSON data from the server when online, but I am now developing an offline mode for the application. Despite trying to tackle the issue, I am unable to identify why I cannot resolve it. In ...

Elusive Appearance of the Flask Flash Message

I have developed a web application using Flask that allows users to upload files to an S3 storage. However, I would like to enhance the user experience by showing them the progress of their file uploads in real-time. To achieve this, I am utilizing Flash t ...

How can I efficiently utilize the date picker feature in Angular JS for a smooth user experience?

I am new to AngularJS and attempting to implement a date picker. I initially tried using a basic jQuery UI date picker, but it did not function as expected. Can someone please provide me with some code that demonstrates the simplest way to achieve this in ...

What is the best way to update and add data with just one click using jQuery?

Trying to dynamically add text to textboxes by clicking an "add" button. The code allows for adding/removing textboxes that save values to and delete from a database. Upon page load, a function called showitem creates textboxes dynamically and populates th ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

Displaying a message when there are no results in Vue.js using transition-group and encountering the error message "children must be keyed

Utilizing vue.js, I crafted a small data filter tool that boasts sleek transitions for added flair. However, I encountered an issue with displaying a message when there are no results matching the current filters. Here's what I attempted: <transit ...

A guide on retrieving and resetting the value of a radio button within a table

I need to create multiple radio buttons within a table using Razor syntax under ASP.NET Core MVC. Each row of the table should have an update and clear link to update the record and clear the selected radio button for that specific row. <table class=&qu ...