Tic-Tac-Toe: The square's value stays unchangeable

Currently, I am working on creating a tic-tac-toe game using pure vanilla Javascript, so I am aiming to keep it as simple as possible. I have run into an issue and need some guidance.

The main requirement is that once a square has been clicked and filled with either an "X" or an "O", it should not be able to be overwritten. Instead, an alert should appear prompting the user to select another square.

Thank you in advance for your help and time!

Below is the code that I have developed so far:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Tic Tac Toe</title>
    <style>
        td {
            border: 1px solid black;
            height: 250px;
            width: 250px;
            font-family: sans-serif;
            font-size: 150pt;
            text-transform: uppercase;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <td align="center" id="square1" onclick="displayMarker('square1');"></td>
            <td align="center" id="square2" onclick="displayMarker('square2');"></td>
            <td align="center" id="square3" onclick="displayMarker('square3');"></td>
        </tr>
        <tr>
            <td align="center" id="square4" onclick="displayMarker('square4');"></td>
            <td align="center" id="square5" onclick="displayMarker('square5');"></td>
            <td align="center" id="square6" onclick="displayMarker('square6');"></td>
        </tr>
        <tr>
            <td align="center" id="square7" onclick="displayMarker('square7');"></td>
            <td align="center" id="square8" onclick="displayMarker('square8');"></td>
            <td align="center" id="square9" onclick="displayMarker('square9');"></td>
        </tr>
    </table>

    <script>
        var cp1 = 1;

        function displayMarker(allSquares) {

            if (cp1==1) {
                document.getElementById(allSquares).innerHTML = "X";
                cp1 = 2;
            }

            else {
                document.getElementById(allSquares).innerHTML = "O";
                cp1 = 1;
            }

    }
    </script>
</body>
</html>

Answer №1

Ensure that the square's value (innerHTML) is not blank. If it is, display an alert message and exit the function.

function showMarker(squareId) {
    var squareElement = document.getElementById(squareId);
    
    if (squareElement.innerHTML.trim() === "") {
        return alert("Please select a different square");
    }
    // ...

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

Dynamic HTML5 elements in constant motion

I'm interested in creating an HTML5 canvas that features bouncing circle and square elements that interact with each other, potentially spinning upon collision. The best example I've come across so far is located at this link. var canvas = docu ...

Is it possible to make a form field inactive based on another input?

I need help with disabling certain form fields until other fields are filled in. You can check out an example of what I'm trying to achieve here: https://jsfiddle.net/fk8wLvbp/ <!-- Bootstrap docs: https://getbootstrap.com/docs --> <div ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

Tips for improving the performance of MongoDB queries in a Node.js environment

I am currently facing an issue with my code running in nodejs where I need to call a MongoDB query with aggregation properties using callbacks. However, the code is not functioning as expected. I want the code to run asynchronously so that once the MongoDB ...

The onchange function in JavaScript is malfunctioning

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Product page</title> <!-- Fonts -- ...

A guide to populating a table with JSON data that includes empty cells in AngularJS

I'm dealing with JSON data that includes employee names and salaries over multiple days (1-5). My goal is to display this information in an HTML table using AngularJS, mimicking the layout of the required table below. JSON Data: [{ name: "Jo ...

Error encountered: A syntax error occurred due to an unexpected token ":" found in the file path D:practise odejs odejs-demoviewsindex.html

Attempting to switch the engine view from .ejs to .html resulted in an error. After searching online, I was unable to find a solution for the following problems: Express 500 SyntaxError: Unexpected token : in D:\practise\nodejs\nodejs-demo& ...

The variable for Google Maps has not been defined

I'm currently working on developing a map that will display multiple markers based on custom posts with metaboxes. The end goal is to have a map showing markers with the post title, some description, and a link to the post. Although I feel like I&apo ...

A guide on integrating MongoDB, Mongoose, Express JS, and Node JS for effectively adding prices

Currently adding various documents to the database: await TestMOdel.insertMany([ { Model: "Samsung", price: 45000, OS: "MS DOS", }, { Model: "Wipro", pr ...

Understanding how to sum the values of two separate dropdown selections using jQuery

Is it possible to combine and total up two different selections to display on the "Total" button below? I have added calculations to each selection. When a user selects a quantity, it should automatically sum up and display on the "Total" button, but I am ...

Photoswipe using identical source code, yet the output is malfunctioning

Having an issue with my code that refreshes the content of a ul element. Initially, it works fine by directly loading the ul content, but I am constantly creating new content every 10 seconds to provide users with fresh updates. Even though the source co ...

Tips on adding a tooltip to the react-bootstrap tab element

How can I add a tooltip to the tabs in my React application using Bootstrap tabs? I have three tabs and I want a tooltip to appear when hovering over each tab. import { Tabs,Tab} from "react-bootstrap"; // inside return <Tabs variant="pills" ...

Create a dynamic feature in Bootstrap4 where the navigation bar changes color as the user scrolls to different sections of the

Currently building my personal portfolio website with Bootstrap 4, I came up with a great idea: changing the navigation bar color based on different sections of the website. I attempted to achieve this using JQuery's offset and scrollTop functions, bu ...

Master the art of fetching response data from an API and implementing a function to process the data and generate desired outputs using Node.js and JavaScript

Being new to node.js, javascript, and vue, I attempted to create a Currency Converter by fetching data from an API for exchange rates and performing calculations in a function. Despite successfully obtaining the exchange rates from the selected country in ...

Encountering the error "Invalid URL. Please provide only absolute URLs" while trying to integrate the Airtable JavaScript library in a Next.js application

I am currently working on a Next JS application that includes a Page called somePage.js. In this page, I am attempting to make an XHR request to the Airtable API from within the getServerSideProps function. The relevant components look like this: pages/so ...

JavaScript Equivalent of jQuery's removeClass and addClass Functions

I am faced with the challenge of rewriting the following code without using jQuery: document.querySelector('.loading-overlay').classList.remove('hidden'); Can anyone provide guidance on how this can be achieved? ...

What strategies can be utilized to enhance the cleanliness of these functions?

Is there a way to avoid adding new lines of JS code every time I add a new image to the HTML? $(document).ready(function() { $('.btn').click(function() { var bid = $(this).attr('id'); if(bid=="img1" || bid == "img2" || bid == "img3"){ ...

JavaScript code to shift a box beyond the boundaries of a grid

I have a yellow square within a grid. Upon clicking the 'UP' button, the yellow square moves up by one box. How can I ensure that the square stops at the edge of the grid and does not move out? let moveCounter = 0; var grid = document.getElem ...

How can I display the value of a radio button that has been chosen?

Would you mind sharing how to display the selected value of a radio button? I attempted it this way, but unfortunately, it did not work. You can view my code at this link. <mat-radio-group [(ngModel)]="favoriteName"> <mat-radio-button *ngFor="l ...

Tips for showcasing Markdown files within subdirectories in Next.JS

In my Next.JS project, I am managing numerous Markdown files that are organized into various category folders. For example, I have folders named 'CategoryOne' and 'CategoryTwo' located at the root level of the project alongside node_mod ...