0

I have a table on my html file and it has 3 rows. I'm trying to add the onclick method to each row dynamically in the windows. onload that would return the row index I am clicking by an alert but it doesn't matter where I click it always returns as if I would click the last row.

Heres my windows.onload on the top of my <script></script> in the <head> tag:

      window.onload = () => {
        var table = document.getElementById("myTableTesting");
        var rows = table.getElementsByTagName("tr");
        for (let i = 0; i < rows.length; i++) {
          var currentRow = table.rows[i];
          console.log('currentRow', currentRow); // < --- HERE IS SHOWING THE CORRECT ROW.
          currentRow.onclick = () => onClickRowTable(currentRow.rowIndex);
        }
      }

      function onClickRowTable(index) {
        alert(index);
        console.log('onClickRowTable', index);
      }

And here is my table:

        <table id="myTableTesting" class="table table-bordered table-hover">
          <thead class="thead-dark" style="text-align: center">
            <tr>
                <th>
                  Nº
                </th>
                <th>
                  Gerencia
                </th>
                <th>
                  DNI
                </th>
                <th>
                  Permiso
                </th>
                <th>
                  EO
                </th>
              </tr>
          </thead>
          <tbody style="text-align: center">
            <tr>
              <td>
                0
              </td>
              <td>
                2134
              </td>
              <td>
                54147890G
              </td>
              <td>
                VE
              </td>
              <td>
                OAFNIE
              </td>
            </tr>
            <tr>
              <td>
                1
              </td>
              <td>
                2534
              </td>
              <td>
                54145820C
              </td>
              <td>
                INVB
              </td>
              <td>
                OAFHIE
              </td>
            </tr>
          </tbody>
        </table>

I let here my HTML for if you would find any clue

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Test</title>
    <script>
      window.onload = () => {
        var table = document.getElementById("myTableTesting");
        var rows = table.getElementsByTagName("tr");
        for (let i = 0; i < rows.length; i++) {
          var currentRow = table.rows[i];
          console.log('currentRow', currentRow);
          currentRow.onclick = () => onClickRowTable(currentRow.rowIndex);
        }
      }

      function addNewRow() {
        let gerencia = document.getElementById("inputGerencia").value;
        let dni = document.getElementById("inputDNI").value;
        let permiso = document.getElementById("inputPermiso").value;
        let eo = document.getElementById("inputEO").value;
        let numero = -1;
        let table = document.getElementById("myTableTesting");
        var row = table.insertRow(-1);
        var cell0 = row.insertCell(0);
        var cell1 = row.insertCell(1);
        var cell2 = row.insertCell(2);
        var cell3 = row.insertCell(3);
        var cell4 = row.insertCell(4);
        row.onclick = () => onClickRowTable(row.rowIndex);
        numero = table.rows.length -2;
        cell0.innerHTML = numero;
        cell1.innerHTML = gerencia;
        cell2.innerHTML = dni;
        cell3.innerHTML = permiso;
        cell4.innerHTML = eo;
        // Hacer selectable la tabla para borrar la fila que seleccione
      }
      
      function onClickRowTable(index) {
        alert(index);
        console.log('onClickRowTable', index);
      }
    </script>
  </head>
  <body>
    <div class="jumbotron text-center">
      <h1>Gestores</h1>
      <p>Prueba técnica de la nueva aplicación web.</p>
    </div>

    <div class="container" style="margin-top: 16px;">
      <table id="myTableTesting" class="table table-bordered table-hover">
          <thead class="thead-dark" style="text-align: center">
            <tr>
                <th>
                  Nº
                </th>
                <th>
                  Gerencia
                </th>
                <th>
                  DNI
                </th>
                <th>
                  Permiso
                </th>
                <th>
                  EO
                </th>
              </tr>
          </thead>
          <tbody style="text-align: center">
            <tr>
              <td>
                0
              </td>
              <td>
                2134
              </td>
              <td>
                54147890G
              </td>
              <td>
                VE
              </td>
              <td>
                OAFNIE
              </td>
            </tr>
            <tr>
              <td>
                1
              </td>
              <td>
                2534
              </td>
              <td>
                54145820C
              </td>
              <td>
                INVB
              </td>
              <td>
                OAFHIE
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <br />
    <div class="container">
        <h3 class="">
            Añadir nuevo campo.
        </h3>
        <div class="column">
          <input id="inputGerencia" type="text" placeholder="Gerencia" class="form-control">
          <br />
          <input id="inputDNI" type="text" placeholder="DNI" class="form-control">
          <br />
          <input id="inputPermiso" type="text" placeholder="Permiso" class="form-control">
          <br />
          <input id="inputEO" type="text" placeholder="EO" class="form-control">
        </div>
        <br />
        <button type="button" class="btn btn-primary btn-block" onclick="addNewRow()">
          Añadir
        </button>
      </div>



    
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>
Pardeep
  • 2,153
  • 1
  • 17
  • 37
SmoggeR_js
  • 2,950
  • 4
  • 22
  • 52

1 Answers1

2

By declaring the variable with var, currentRow always contains the last value from the loop:

Try table.rows[i].rowIndex instead of currentRow.rowIndex

OR: Declare the variable currentRow with let instead of var which will create block scope for the variable.

let currentRow = table.rows[i];

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Test</title>
    <script>
      window.onload = () => {
        var table = document.getElementById("myTableTesting");
        var rows = table.getElementsByTagName("tr");
        for (let i = 0; i < rows.length; i++) {
          let currentRow = table.rows[i];
          //console.log('currentRow', currentRow);
          currentRow.onclick = () => onClickRowTable(currentRow.rowIndex);
        }
      }

      function addNewRow() {
        let gerencia = document.getElementById("inputGerencia").value;
        let dni = document.getElementById("inputDNI").value;
        let permiso = document.getElementById("inputPermiso").value;
        let eo = document.getElementById("inputEO").value;
        let numero = -1;
        let table = document.getElementById("myTableTesting");
        var row = table.insertRow(-1);
        var cell0 = row.insertCell(0);
        var cell1 = row.insertCell(1);
        var cell2 = row.insertCell(2);
        var cell3 = row.insertCell(3);
        var cell4 = row.insertCell(4);
        row.onclick = () => onClickRowTable(row.rowIndex);
        numero = table.rows.length -2;
        cell0.innerHTML = numero;
        cell1.innerHTML = gerencia;
        cell2.innerHTML = dni;
        cell3.innerHTML = permiso;
        cell4.innerHTML = eo;
        // Hacer selectable la tabla para borrar la fila que seleccione
      }
      
      function onClickRowTable(index) {
        alert(index);
        console.log('onClickRowTable', index);
      }
    </script>
  </head>
  <body>
    <div class="jumbotron text-center">
      <h1>Gestores</h1>
      <p>Prueba técnica de la nueva aplicación web.</p>
    </div>

    <div class="container" style="margin-top: 16px;">
      <table id="myTableTesting" class="table table-bordered table-hover">
          <thead class="thead-dark" style="text-align: center">
            <tr>
                <th>
                  Nº
                </th>
                <th>
                  Gerencia
                </th>
                <th>
                  DNI
                </th>
                <th>
                  Permiso
                </th>
                <th>
                  EO
                </th>
              </tr>
          </thead>
          <tbody style="text-align: center">
            <tr>
              <td>
                0
              </td>
              <td>
                2134
              </td>
              <td>
                54147890G
              </td>
              <td>
                VE
              </td>
              <td>
                OAFNIE
              </td>
            </tr>
            <tr>
              <td>
                1
              </td>
              <td>
                2534
              </td>
              <td>
                54145820C
              </td>
              <td>
                INVB
              </td>
              <td>
                OAFHIE
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <br />
    <div class="container">
        <h3 class="">
            Añadir nuevo campo.
        </h3>
        <div class="column">
          <input id="inputGerencia" type="text" placeholder="Gerencia" class="form-control">
          <br />
          <input id="inputDNI" type="text" placeholder="DNI" class="form-control">
          <br />
          <input id="inputPermiso" type="text" placeholder="Permiso" class="form-control">
          <br />
          <input id="inputEO" type="text" placeholder="EO" class="form-control">
        </div>
        <br />
        <button type="button" class="btn btn-primary btn-block" onclick="addNewRow()">
          Añadir
        </button>
      </div>



    
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    Whaaaaaaat? It worked! I cannot mark it as correct up to 4 min left but I will. Meanwhile, could you explain me why with let works but it doesn't with var? Thanks a lot! :D – SmoggeR_js Aug 07 '19 at 10:21
  • 1
    @MtgKhaJeskai, I will request you to visit https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var – Mamun Aug 07 '19 at 10:28