[Solved] Naughts and crosses in JavaScript [closed]


The issue with your code is that when you set the onclick property of all your cells, you actually calling the function, thus running the code within it. You don’t want this to happen as you only want it to do this when you click on a cell. So what you can do is wrap your function call within another function. This allows you to click the onclick button so it will then call the function within the function (allowing you to pass arguments into your ex function). This will solve your issue with the code you currently have, however, if you wish to dynamically create elements you can use the for loop at the bottom of your code.

However, there is a small issue with this for-loop. You need to change var to let in

for(var count = 1; ...)

the reason as to why is because var will make it so all your function calls have the same value of choice which is 10 – the last value of count, whereas you instead want to have incrementing values 1, 2, 3 etc.... Fixing this will resolve your issue.

See working example below:

var table = ["-", "-", "-", "-", "-", "-", "-", "-", "-"];
var player = 1;

function ex(choice) {
  console.log(choice);
  if (player == 1) {
    table[choice - 1] = "X";
    player = 0;
  } else {
    table[choice - 1] = "O";
    player = 1;
  }
  console.log(player + " is playing");
  for (var i = 1; i < 10; i++) {
    document.getElementById("cell" + i).innerHTML = table[i - 1];
  }
}


for (let count = 1; count < 10; count++) {
  document.getElementById("cell" + count).onclick = function() {
    ex(count)
  };
}
<table cellpadding="5" border="1">
  <tbody>
    <tr>
      <td id="cell1">-</td>
      <td id="cell2">-</td>
      <td id="cell3">-</td>
    </tr>
    <tr>
      <td id="cell4">-</td>
      <td id="cell5">-</td>
      <td id="cell6">-</td>
    </tr>
    <tr>
      <td id="cell7">-</td>
      <td id="cell8">-</td>
      <td id="cell9">-</td>
    </tr>
  </tbody>
</table>

2

solved Naughts and crosses in JavaScript [closed]