Kotojo
Kotojo

Reputation: 11

How to access single td of full table - Jquery

I am trying to set up a simple tic tac toe game and made a table with 3 rows each with 3 cells. I am trying to make it so when I click on one td then it will change the text of that td without having to give each td it's own class. http://jsbin.com/yuvatejagu/1/edit This is the way I was trying to do it currently, but am failing terribly. Any help would be appreciated.

Upvotes: 0

Views: 51

Answers (3)

daremachine
daremachine

Reputation: 2788

This is working. Btw funny game.

$(document).ready(function() {

      var nextTurn = 'X';

      $("td").click(function() {
        var self = $(this);

        if(self.text() == '') {
          self.text(nextTurn);

          switch(nextTurn)
          {
            case 'X':
              nextTurn = 'O';
              break;
            case 'O':
              nextTurn = 'X';
              break;
          }

        }
      });
    });

Upvotes: 0

Dan Simmons
Dan Simmons

Reputation: 116

$(document).ready(function() {

 turn = "X";


$("td").click(function(event){
  if($(this).text() === 'X' || $(this).text() === '0')
     alert('choose again');
   else
     $(this).text(turn);

  });
});

Upvotes: 1

Travis
Travis

Reputation: 699

Looks like there are a couple issues. One, you don't need to do the .get(0) with the target element. Second, you need to provide the full test for the X case. Where you have || "X " you need to repeat the target.text() call. Try this for the js:

$(document).ready(function() {
    turn = "X";

    function handler( event ) {
        var target = $(event.target);
        if (target.text() === "O" || target.text() === "X"){
          alert("Choose again!");
        }
        else {
          target.text(turn);
        }
    }

    $("td").click(handler);
});

Note: You will of course still need to add additional logic to toggle which turn it is, etc.

Upvotes: 1

Related Questions