javascripthtmldynamic-tables

how to apply more than one indexing in a single statement


I am working on the dynamic table in which the javascript reads the tables then responds to it respectively to the tables' columns. I wished to use the row in the col statement for example col = x[i].rows[row].cells.length; instead.

function add() {
  var x, y, z, i, j, row, col;
  x = document.querySelectorAll(".tab");

  for (i = 0; i < x.length; i++) {
    y = x[i].insertRow();

    row = parseInt(x[i].rows.length);
    col = x[i].rows[1].cells.length; //should get the length of last row of the table
    for (j = 0; j < col; j++) {
      if (j == 0) {
        y.insertCell(j).innerHTML = "<input type='checkbox'>";
      } else {
        y.insertCell(j).innerHTML = row;
      }
    }
  }
}
<table border=1 class="tab">
  <tr>
    <td colspan=3>Table 1</td>
  </tr>
  <tr>
    <td><input type="checkbox"></td>
    <td>c1</td>
    <td>c2</td>
  </tr>
</table><br>
<table border=1 class="tab">
  <tr>
    <td colspan=3>Table 2</td>
  </tr>
  <tr>
    <td><input type="checkbox"></td>
    <td>c1</td>
    <td>c2</td>
  </tr>
</table>
<button onclick="add()">add</button>


Solution

  • You should separate header <tr>s and body <tr>s with respective grouping tags. Then you can get <tr>s in body alone by using something like this x[i].tBodies[0].rows.length. Example has only one tbody tag thus directly reading 0 index.

    function add() {
      var x, y, z, i, j, row, col;
      x = document.querySelectorAll(".tab");
    
      for (i = 0; i < x.length; i++) {
        y = x[i].insertRow();
    
        row = x[i].tBodies[0].rows.length;
        col = x[i].rows[row - 1].cells.length; //should get the length of last row of the table
        for (j = 0; j < col; j++) {
          if (j == 0) {
            y.insertCell(j).innerHTML = "<input type='checkbox'>";
          } else {
            y.insertCell(j).innerHTML = row;
          }
        }
      }
    }
    <table border=1 class="tab">
      <thead>
        <tr>
          <td colspan=3>Table 1</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input type="checkbox"></td>
          <td>c1</td>
          <td>c2</td>
        </tr>
      </tbody>
    </table>
    <button onclick="add()">add</button>