1

I've been trying to get this data, but the array comes out empty:

function saveData() {
  var tableData = [];
  var table = document.getElementById("dtable");
  console.log(table)

  for (var i = 0; i < table.length; i++) {
    let tableCells = table.rows.item(i).cells;
    let cellLength = tableCells.length;

    for (let j = 0; j < cellLength; j++) {
      let cellVal = tableCells.item(j).innerHTML;
      tableData.push(cellVal)
    }
  }
  console.log(tableData)
  rows = JSON.stringify(tableData);
  google.script.run.formToSheets(rows);
}

Thanks for any help! enter image description here

Rubén
  • 34,714
  • 9
  • 70
  • 166
onit
  • 2,275
  • 11
  • 25
  • Related: [How do I iterate through table rows and cells in JavaScript?](https://stackoverflow.com/q/3065342/1595451) – Rubén May 17 '22 at 01:39

1 Answers1

2

In your script, as one of several possible modifications, how about the following modification?

From:

var tableData = [];
var table = document.getElementById("dtable");
console.log(table)

for (var i = 0; i < table.length; i++) {
  let tableCells = table.rows.item(i).cells;
  let cellLength = tableCells.length;

  for (let j = 0; j < cellLength; j++) {
    let cellVal = tableCells.item(j).innerHTML;
    tableData.push(cellVal)
  }
}
console.log(tableData)

To:

var table = document.getElementById("dtable");
console.log(table)

var [, ...tr] = table.querySelectorAll("tr");
var tableData = [...tr].map(r => {
  var td = r.querySelectorAll("td");
  return [...td].map((c, j) => j != 3 ? c.innerHTML : c.querySelectorAll("select")[0].value);
});
console.log(tableData)
  • In this modification, from a table, the table rows are retrieved. And, the table cells are retrieved from the table rows. In teh case of the dropdown list, the value is retrieved from the dropdown list.

Note:

  • When this modification was not the direct solution to your issue, I think that when you provide your whole script, it will help to correctly understand your question.
Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • @santosOnit Thank you for replying and testing it. I'm glad your issue was resolved. Thank you, too. – Tanaike May 17 '22 at 01:41