2

I want the onclick function to remember the value of the variable i and j in the for loop at the instance the onclick function is called. However the variables update before they are stored in the onclick function.

I am making a Tic Tac Toe application and don't want to manually add all the onclick statements as that would be a bad practice for larger projects.

for (j = 0; j < Columns; j++) {

    var col = document.createElement("td")
    row.appendChild(col)
    col.id = i + "" + j;
    col.onclick = function() {
        console.log(i, j)
        place(i + "" + j)
    }    
}

There are no error messages but I don't know how to save the variables the instance the onclick function is called. How can I save the variables when the onclick function is called?

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48

1 Answers1

4

You must scope your variables declaring it by the use of let, that way you'll scope it exclusively for that iteration. Avoid to declare a variable like i = 0, bacause that way you create a global variable and it will not work (throw an error) on 'use strict' cases.

let Columns = 3
let rows = 3
const table = document.getElementById("table")

for (let i = 0; i < rows; i++) {  
  let row = document.createElement("tr");
  row.textContent = "row " + i;
  table.appendChild(row)
  for (let j = 0; j < Columns; j++) {
      var col = document.createElement("td")
      row.appendChild(col)
      col.id = i + "" + j;
      col.onclick = function() {
          console.clear()
          console.log(i, j)
      }    
  }
}
tr, td{
  border: 1px solid;
  min-height: 60px;
  min-width: 60px;  
}
<table id="table"></table>

If you can't use let (maybe because it is ES6), you can use the common var, but then you'll need to bind the values on the function, as the code below shows:

var Columns = 3
var rows = 3
var table = document.getElementById("table")

for (var i = 0; i < rows; i++) {  
  var row = document.createElement("tr");
  row.textContent = "row " + i;
  table.appendChild(row)
  for (var j = 0; j < Columns; j++) {
      var col = document.createElement("td")
      row.appendChild(col)
      col.id = i + "" + j;
      col.onclick = function(rowI, colJ) {
          console.clear()
          console.log(rowI, colJ)
      }.bind(this, i, j) //bind parameters -> this is the context
  }
}
tr, td{
  border: 1px solid;
  min-height: 60px;
  min-width: 60px;  
}
<table id="table"></table>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48