Home > Back-end >  Problems With Javascript Tick Tack Toe Game
Problems With Javascript Tick Tack Toe Game

Time:10-16

I'm trying to create a tick tack toe game using javascript. I've posted my code up in github, here: https://github.com/chaneth8/Tick-Tack-Toe. The main problem I'm having is with updating the users' names. I created a form for users to add their names in, as seen on the top of the page: [![enter image description here][1]][1]

When users enter their names into the form however, the headings that say "Player one is" and "Player two is:" remain unchanged. A similar thing happens when a user wins a game. Again, their name isn't displayed - it just says "won" at the bottom of the page, instead of " won", even after both users enter their name into the form at the top of the page. The way my code works is as follows: I wrote the following HTML for my form:

    <div id = "input-form">
        <form onsubmit='return Newgame.startGame()' name = 'form' id = 'form'>
            Input Player 1's Name:<input type= 'text' name='player1'>
            Input Player 2's Name:<input type= 'text' name='player2'>
            <input type='submit' value='Submit'>
        </form>

    </div>

I then defined a factory function, in Javascript, that had the function startGame in it:

   const game = () => {

        let Board = [[2,2,2], [2,2,2], [2,2,2]];
        let Current_player = 0;
        let player0 = "";
        let player1 = "";

        const startGame = () => {
            player0 = document.forms["form"]["player1"].value; 
            player1 = document.forms["form"]["player2"].value;

            clear();
            Initialize();
        }

I then called an instance of the factory function at the bottom of the page:

    let Newgame = game();
    Newgame.Initialize();

I'm wondering why these issues are happening, and how I can fix it. Thanks in advance.

CodePudding user response:

You need to prevent the form from being submitted, after onSubmit the page refreshes and the value of player0 and player 1 is lost

pass the event in the onSubmit

onsubmit="return Newgame.startGame(event)"

end prevent in startGame

 const startGame = event => {
        event.preventDefault();
        ...
  • Related