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

What steps do I need to take to develop a CLI application similar to ng, that can be installed globally on the system

Upon installing npm i ng -g How does the system determine the installation path? I am interested in creating an application that can be installed and executed similarly. ...

Concealing the sidebar in React with the help of Ant Design

I want to create a sidebar that can be hidden by clicking an icon in the navigation bar without using classes. Although I may be approaching this incorrectly, I prefer to keep it simple. The error message I encountered is: (property) collapsed: boolean ...

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...

Guide on how to style and arrange multiple checkboxes in both horizontal and vertical rows using CSS

Is it possible to align a collection of checkboxes both vertically and horizontally, even when the labels vary in size? I found an example that demonstrates vertical alignment. Click here to view. How can I neatly arrange these checkboxes so that they ar ...

Adjusting the width of an element by modifying its border-collapse property

Is there a way to implement "border-collapse: collapse" without affecting the width of the element? The Issue: Without using the border-collapse property, the right and left borders appear bold because they are adjacent. Using the border-collapse propert ...

Google Map in Bootstrap FullScreen Mode Not Mobile-Friendly

Could you please take a look at the provided link and advise me on why the map is not responding correctly? I am also facing issues with the positioning of the map on the page, so any guidance on adjusting it appropriately would be greatly appreciated. Be ...

Troubleshooting the malfunctioning of the edit record feature in Python Django when using Jquery

Scenario: My HTML table displays data for a specific user with delete and edit buttons next to each row. While the delete button functions correctly, clicking the edit button does not trigger any action despite following a similar approach. This snippet o ...

The toggleCategories function seems to be malfunctioning as it is only showing the sequence number as 0 in ReactJS

I am currently working on a portfolio using the React framework. One of the features I have implemented is a project page where multiple projects are displayed within tabs. However, I am facing some issues with the functionality. toggleCategories(){ ...

hierarchical browsing system

Take a look at the image provided below. Currently, I am using multiple unordered lists - specifically 5. However, I would prefer to consolidate them all into a single nested ul. I am encountering two issues: How can I add a border-bottom to the hori ...

Blazor components experience element interaction while utilizing more than one instance of Blazorise.Bootstrap component

I am facing an issue in my Blazor app where a component with a button and bootstrap collapse works fine when used once on a page, but triggers collapse elements in other instances when used multiple times. This seems to be happening because their IDs are s ...

Adjusting images of various sizes within a single row to fit accordingly

I am faced with a challenge of aligning a set of images on a webpage, each with varying heights, widths, and aspect ratios. My goal is to arrange them in a way that they fit seamlessly across the screen while ensuring their heights are uniform. Adjusting ...

Can you show me a method to integrate this HTML and CSS code into a Teachable page successfully?

Hey there, I've been encountering some challenges while working with HTML and CSS on a platform known as Teachable. Essentially, I'm aiming to create a layout with 2 columns: - Column 1 - Image - Column 2 - Text Whenever I apply <div class=" ...

Getting duplicate tokens for multiple users while utilizing Firebase messaging

When attempting to acquire a token from firebase, I employ the code snippet provided below: const messaging = firebase.messaging(); messaging.requestPermission() .then(() =>{ return firebase.messaging().getToken(); }).then(token => { s ...

A Vue.js trick to modify the element's class within a v-for loop when hovering in and out

I'm having trouble changing the class of a single element within a v-for loop based on mouseenter/mouseleave events. I want only the hovered element to change its class, but currently, all elements in the list are affected. I attempted binding the cl ...

Be warned: Babel has detected a duplicate plugin or preset error

Currently, I am enrolled in a React course on Frontend Masters. As part of the course, we were tasked with modifying the Babel config to allow state instantiations like: state = {index: 0} in class components. However, when I executed the command: npm i ...

React's constructor being invoked twice

As a newcomer to react, I am in the process of developing a simple web application but encountering an issue. It seems like my Constructor is being called twice when I load a class component. Can anyone provide some assistance? Home.js import React from ...

Collaboratively accessing a shared constant in two separate JavaScript files

I am diving into the world of JavaScript and Node.js. I am currently experimenting with Puppeteer to extract the text value of a tag and store it in a constant variable. However, I am encountering difficulties when trying to integrate this value into my ...

Troubleshooting: Resolving issues with Vue's global EventBus in my project

I am using Vue.js within a Laravel project and I am encountering an issue with the global event bus. I have created an event-bus.js file and imported it where needed. Although events are being generated upon clicking, there seems to be no reactions from th ...

Angular paginator encountered an issue while attempting to parse the template

I'm updating my data list to include pagination, and everything seems fine with retrieving data and sorting. However, when I add the paginator tag to my template, Angular shows me an error: ERROR in Errors parsing template: Unexpected closing tag " ...

Tips for passing parameters in an AJAX request

I have a single AJAX call that requires passing parameters to my function. Below is the AJAX call implementation: $.ajax({ url: 'lib/function.php', data: { action: 'getStoreSupplyItems', id: store_id, ...