Skip to content
Advertisement

The top two rows of a table not working in Html while using JS

I want to create a Tic Tac game but there is some problem probably in Javascript file thats why when any of the boxes of top row are clicked they are not responding … while the third one does Please help

var move = 1;
var play = true;

$("#board tr td").click(function() {

  if ($(this).text() == "" && play == true) {
    if ((move % 2) == 1) {
      $(this).append("X");
    } else if ((move % 2) == 0) {
      $(this).append("O");
    }
    move++;
  } else {
    console.log("Enter correct input");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table align="center" id="board">
  <tr>
    <td> </td>
    <td> </td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
    <td> </td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

Advertisement

Answer

It’s always a bit tricky to relay on the text() of a cell being "" because there might be some space left in the markup which can invalidate your condition.

To quickly fix the issue you can add trim() to make sure to remove all leading and trailing space in the markup.

I’ve created a JSFiddle to show the working implementation: https://jsfiddle.net/sandro_paganotti/6wdha0rx/10/

var move = 1;
var play = true;

$("#board tr td").click(function() {
  if ($(this).text().trim() == "" && play == true) {
    if ((move % 2) == 1) {
      $(this).append("X");
    } else if ((move % 2) == 0) {
      $(this).append("O");
    }
    move++;
  } else {
    console.log("Enter correct input");
  }
});
Advertisement