0

I have a javascript code for creating a row of a table:

function create_row() {
    var table = document.getElementById("main_table");
    var n = table.rows.length;
    var m = table.rows[0].cells.length;
    var row = table.insertRow(n);
    for (i=2; i<m; i++) {
        var cell = row.insertCell(i);
        cell.innerHTML = "<input size=4>";
        cell.addEventListener("change", function () {
            console.log("Column of a cell: " + cell.cellIndex);
        })
    }
}
document.getElementById('create_row').onclick = create_row;

My intention is that when a user types something in the cell, I want to print that value. However, cellIndex is always the number of columns in my table (or m) (as I understand, because the cell is clicked after all cells are created, and thus i reached m).

How can I receive row, column, and the value of a cell when the content of it was changed?

Sergey Ivanov
  • 3,719
  • 7
  • 34
  • 59
  • 1
    Maybe: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Apr 15 '15 at 14:44
  • I was about to post this as an answer, but it got duped while I was checking it. When you generate each cell, you can give it a custom attribute combination - i.e. `` Then in your `change` listener, make the function pass that value back, like this: `cell.addEventListener("change", function () { console.log("Row " + this.getAttribute('row') + " Column " + this.getAttribute('column')); // call the function with those values as arguments })` Here's an example: https://jsfiddle.net/opf16x7y/ – Josiah Apr 15 '15 at 14:56

1 Answers1

1

Oooh, Javascript closures. Try this:

function create_row() {
  var table = document.getElementById("main_table");
  var n = table.rows.length;
  var m = table.rows[0].cells.length;
  var row = table.insertRow(n);
  for (i=2; i<m; i++) {
    create_cell(i);
  }
}

function create_cell(){
  var cell = row.insertCell(i);
  cell.innerHTML = "<input size=4>";
  cell.addEventListener("change", function () {
    console.log("Column of a cell: " + cell.cellIndex);
  })
}

document.getElementById('create_row').onclick = create_row;
Tadeáš Peták
  • 567
  • 2
  • 13