Is there a way to update the button's value upon clicking it?

I've hit a roadblock in my tic tac toe game project during class, and I've been struggling for the past two days to get the X's and O's to show up. The deadline for this assignment is tomorrow! Here are the task requirements:

COMPSCI20: Tic Tac Toe Assignment

Create an HTML file that includes the following elements:

  • a page title and a link to a CSS file
  • a header division (with an ID) containing text
  • a main division (with an ID) with a 3x3 table of clickable buttons (each button having IDs and classes)
  • a footer division (with an ID) containing text Title + Links  Main + Table  Header  Footer 

The CSS file should style the content as follows:

  • define font, background color, text alignment, and padding for the header
  • set the background color and padding for the main division
  • buttons should have defined height, width, font, background color, and border properties
  • customize the font, background color, text alignment, and padding for the footer

Create a JavaScript file that includes two global variables: one to store the player turn (X or O) and another to store the winner. The JS file should contain the following functions:

  • a Start() function that initializes the player turn as X and the winner as null
  • a ChooseSquare() function that assigns the appropriate letter to the clicked button, disables it, and switches to the other player’s turn
  • a CheckWin() function that checks for each possible winning combination and displays a message in the footer if a player has won

This is the JavaScript code I have so far:

var winner;
var current;

function Start() {
  current = "x";
}

... (remaining script omitted for brevity)

</html>

Answer №1

Checking if the "button1" is clicked using document.getElementById("button1").onclick
is not the correct way. This code snippet only checks if the onclick property has any value, which it does because it contains the value of onclick="ChooseSquare()" attribute.

To rectify this issue, you should modify the function to take a parameter. By passing this as an argument to the function, it can be used to update the button that the user clicked on.

Additionally, in the CheckWin() function, you need to retrieve the values of the buttons, and the IDs should be assigned to the <button> elements instead of the <td>s.

In the reset() function, there was a usage of variables like one, two, etc., which were local to the CheckWin function. I have revised it to iterate over all elements with class="button".

var winner;
var current;

function Start() {
  current = "x";
}

function ChooseSquare(button) {
  button.value = current;
  current = (current == "x") ? "o" : "x";
  button.disabled = true; // Prevent clicking button twice
  CheckWin();
}

function CheckWin() {
  var one = document.getElementById("button1").value;
  var two = document.getElementById("button2").value;
  var three = document.getElementById("button3").value;
  var four = document.getElementById("button4").value;
  var five = document.getElementById("button5").value;
  var six = document.getElementById("button6").value;
  var seven = document.getElementById("button7").value;
  var eight = document.getElementById("button8").value;
  var nine = document.getElementById("button9").value;
  //x wins
  if (one == "x" && two == "x" && three == "x") {
    window.alert("player1 has won")
  }
  if (one == "x" && four == "x" && seven == "x") {
    window.alert("player1 has won")
  }
  if (one == "x" && five == "x" && nine == "x") {
    window.alert("player1 has won")
  }
  // Additional x win conditions...
  
  //o wins
  if (one == "o" && two == "o" && three == "o") {
    window.alert("player2 has won")
  }
  // Additional o win conditions...
}

function reset() {
  Array.from(document.querySelectorAll(".button")).forEach(b => {
    b.value = " ";
    b.disabled = false;
  });
}
#Header {
  background-color: Red;
  color: white;
  text-align: center;
  font-family: Acme, Arial, sans-serif;
  padding: 5px;
}

#Main {
  margin-left: 200px;
  margin-right: 100px;
  padding: 0px;
  background-color: white;
}
/* Additional CSS rules... */

Answer №2

I simply can't resist...

const main    = document.querySelector('#Main')
  ,   All_bt  = document.querySelectorAll('#Main > button')
  ,   btReset = document.querySelector('#bt-reset')
  ;
var current = 0
  , players = [ { cod: 'x', case: [ ] } 
              , { cod: 'o', case: [ ] } 
              ]
    ;
main.onclick=e=>
  {
  if (e.target.tagName.toLowerCase() !== 'button') return;
  e.target.textContent = players[current].cod;
  e.target.disabled = true
  players[current].case.push( e.target.id.slice(-3))

// check win...
    let Win = false
      , Kaz = []
    for(i=1;i<4;i++)
      {
      Kaz = players[current].case.filter(K=>Number(K.charAt(0))===i)
      if (Kaz.length===3) { Win=true; break }
      Kaz = players[current].case.filter(K=>Number(K.charAt(2))===i)
      if (Kaz.length===3) { Win=true; break }
      }
    if (!Win)
      {
      Kaz = players[current].case.filter(K=>K==='1-1' || K==='2-2' || K==='3-3')
      Win = (Kaz.length===3)
      }
    if (!Win)
      {
      Kaz = players[current].case.filter(K=>K==='1-3' || K==='2-2' || K==='3-1')
      Win = (Kaz.length===3)
      }
   // console.log(Win)

    if (Win)
      {
      All_bt.forEach(bt=>
        { 
        bt.disabled=true
        if ( Kaz.includes(  bt.id.slice(-3)  ))
          { bt.className='Win' }
        })
      }
  current = ++current %2
  }

btReset.onclick=_=>
  {
  current = 0
  players[0].case.length = 0
  players[1].case.length = 0
  All_bt.forEach(bt=>{ bt.disabled=false; bt.textContent = '\u00a0'; bt.className='' })
  }
#Main {
  display: block;
  --bt-size : 50px;
  width:180px;
}
#Main > button {
  display: inline-block;
  width: var(--bt-size);
  height: var(--bt-size);
  margin: 2px;
  font-size: 30px;
  font-weight: bold;
  text-align: center;
  padding: 0;
}
.Win {
  background-color: turquoise;
}
#bt-reset { margin: 1em;}
<div id="Main">
  <button id="bt-1-1">&nbsp;</button>
  <button id="bt-1-2">&nbsp;</button>
  <button id="bt-1-3">&nbsp;</button>
  <button id="bt-2-1">&nbsp;</button>
  <button id="bt-2-2">&nbsp;</button>
  <button id="bt-2-3">&nbsp;</button>
  <button id="bt-3-1">&nbsp;</button>
  <button id="bt-3-2">&nbsp;</button>
  <button id="bt-3-3">&nbsp;</button>
</div>

<button id="bt-reset">reset</button>

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

Error message: When attempting to create dynamic inputs in React, an error occurs stating that instance.render is not

I encountered an issue while attempting to create dynamic inputs in React. The error message 'TypeError: instance.render is not a function' keeps popping up. import React, { Component } from 'react'; import Input from '../../Ui/Inp ...

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

Having trouble with the input range slider on Chrome? No worries, it's working perfectly fine

I'm currently facing an issue with an input range slider that controls the position of an audio track. It seems to work perfectly in Firefox, but in Chrome, the slider gets stuck and doesn't move when dragged. There is a function in place that up ...

What steps should we take to ensure that the container beside the fixed left navigation bar is responsive?

Currently, I am working on creating a user interface that features a fixed navigation bar on the left hand side and a responsive content window. Here is what I have implemented so far: <div style="width: 15%; float: left; display: inline;"> <na ...

Store the running of a JavaScript file in memory

It seems highly unlikely that achieving the following is possible without expert confirmation: On page number 1, user and application data is requested as soon as the page loads. Page number 2 utilizes the same script, so requesting the same information w ...

PHP loaded HTML does not allow JavaScript to execute

My system includes an announcements feature where all announcements are retrieved from a database and displayed on the screen using Ajax and PHP. Below is the code snippet used to load each announcement onto the page: echo '<div id="announcements ...

What is the best way to reduce the size of an image using a URL?

As I work on creating a website in React for a company, my main focus is on developing a drive repository where users can upload files. One issue that has arisen is the performance of the "photos" folder, as it contains numerous high-resolution images th ...

DiscordJS bot using Typescript experiences audio playback issues that halt after a short period of time

I am currently experiencing difficulties with playing audio through a discord bot that I created. The bot is designed to download a song from YouTube using ytdl-core and then play it, but for some reason, the song stops after a few seconds of playing. Bel ...

Remove the boundaries from the grid and only retain the box

I am not skilled in css, but I simply want to eliminate the interior edges of the box and retain only the outer edges. .grid-container { display: grid; grid-template-columns: auto auto auto; background-color: #2196F3; padding: 10px; } .grid-ite ...

How can I showcase API information on a website with the help of Node.js?

Hello everyone, I'm a beginner at creating websites and I am eager to explore nodejs. Currently, I am utilizing an API to retrieve data in node: request(options, function (error, response, body) { if (error) throw new Error(error); console.log(b ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

Utilize Laravel to trigger a route action based on a dropdown selection change, generating a unique URL

In my code, I have a dropdown select containing the list of the next 12 months: <select name="month" id="specificMonth"> @foreach(Carbon\CarbonPeriod::create(now()->startOfMonth(), '1 month', now()->addMon ...

React router updates the URL without affecting the actual display

I am facing an issue in my React project where the URL changes when clicking a link, but the view does not update. I have a separate route and links file, and I can't seem to figure out the problem. Here is my index.js: import React from 'react ...

Reactivating a React hook following the execution of a function or within a function in ReactJS

A new react hooks function has been created to retrieve data from an API and display it on the page: function useJobs () { const [jobs, setJobs] = React.useState([]) const [locations, setLocations] = React.useState({}) const [departments, setDepartm ...

Preventing responsive elements from loading with HTML scripts

Currently, I am utilizing the Gumby framework which can be found here. Everything appears to be running smoothly. My goal is to incorporate a mobile navigation list where the links are grouped under a single button, as outlined here. Initially, this funct ...

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...

Struggling to concatenate array dynamically in Vue using ajax request

I am working on a Vue instance that fetches objects from a REST endpoint and showcases them on a web page. Most parts of the functionality work smoothly like filtering, however, there is an issue when attempting to add new objects by requesting a new "page ...

Develop a feature within a standard plugin that allows users to add, remove, or refresh content easily

I have developed a simple plugin that builds tables: ; (function ($, window, document, undefined) { // Define the plugin name and default options var pluginName = "tableBuilder", defaults = { }; // Plugin constructor func ...

Having difficulty integrating JSON data from a PHP page into jQuery

I'm having trouble parsing JSON data sent from a PHP page using jQuery. The result I'm getting is just an opening curly brace: { I'm not sure how to fix it. In my PHP code, I'm creating the JSON data like this: $load_op_cm = $DBM -> ...

The presence of Vue refs is evident, though accessing refs[key] results in an

I am facing an issue with dynamically rendered checkboxes through a v-for loop. I have set the reference equal to a checkbox-specific id, but when I try to access this reference[id] in mounted(), it returns undefined. Here is the code snippet: let id = t ...