Adding values from a TD with javaScript

0

Good afternoon, I have a script that helped me do it right here, which creates a table after reading information from a textarea. After the table is ready I wanted to sum the values from one of the table columns. I can even calculate the total when the data is entered for the first time, but if I add a row or delete a row I can not update that value, then I thought of creating a function to recalculate this value and call it whenever I make a change in the table. I created the function only that it does not work well, it keeps repeating several times the same field and in the second line for example it does not return the data only the word undefined

Follow the code that generates the table.

function addItens () 
{
   let total =0;
   // Elemento textarea:
   const texto = $("#texto");

    // Elemento table:
    const table = $("#products-table");

    // Divide o conteúdo de textarea em linhas:
    let linhas = texto.val().split("\n");

    // Percorre todas as linhas:
    for (i in linhas)
    {
      // Verifica se a linha não está vazia:
      if (linhas[i])
      {
        // Divide o conteúdo da linha em colunas:
        let retorno = linhas[i].split(" ");

        // Cria uma nova linha na tabela:
        let newRow = $("<tr>");

      // Percorre todas as colunas:
      for (j in retorno)
      {
        // Verifica se a coluna não está vazia:
      if (retorno[j])
      {
        // Cria a nova coluna na tabela:
        let newCol = $("<td>");
        // Adiciona o conteúdo na coluna:
        newCol.html(retorno[j]);

        // Adiciona a coluna na linha:
        newRow.append(newCol);
    }
  }

  total += parseInt(retorno[2]);
 // alert(total);

  // Cria a coluna de ação:
  let action = $("<td>");

  // Adiciona a classe "actions":
  action.addClass("actions");

  // Adiciona o botão Remover à coluna de ação:
  action.html('<button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button>');

  // Adiciona a coluna na linha:
  newRow.append(action);

  // Adiciona a linha na tabela:
    table.append(newRow);
   }
 }

Here is the function I created to scroll through the table and get the value of the column I need

function calculaTotal(){

var table = $("#products-table");
var linhas = document.getElementsByTagName("tr");
var colunas = document.getElementsByTagName("td");
for (i in linhas){
for(j in colunas){
    alert(colunas[i].innerText);
  };
 }
    
asked by anonymous 08.05.2017 / 22:58

2 answers

0

This your attempt to mix jQuery with JavaScript vanilla just to select elements of the DOM was very strange. It works, but there's no need to do it, it leaves the code inconsistent. If you are using jQuery, take advantage of the functionality of it, since you want to manipulate the DOM and that is exactly what it was created for.

With the #products-table tr td:nth-child(1) selector, you are selecting all the first columns of each row. To sum them, just iterate over them and accumulate their value in a variable, returning this variable to the end. To make it more generic, you can pass by parameter the desired column.

See the example:

function getTotal(column = 1) {
  let result = 0;
  let columns = $("#products-table tr td:nth-child(" + column + ")");

  columns.each(i => {
    result += parseInt($(columns[i]).html());
  });

  return result;
}

console.log("Soma da primeira coluna: " + getTotal(1));
console.log("Soma da terceira coluna: " + getTotal(3));
console.log("Soma da quarta coluna: " + getTotal(4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="products-table" border="1">
  <tbody>
    <tr>
      <td>10</td>
      <td>produto1</td>
      <td>1</td>
      <td>3</td>
      <td class="actions"><button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button></td>
    </tr>
    <tr>
      <td>20</td>
      <td>prodto2</td>
      <td>2</td>
      <td>4</td>
      <td class="actions"><button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button></td>
    </tr>
  </tbody>
</table>

So you can call the getTotal function whenever necessary.

    
09.05.2017 / 04:02
0

Try this:

function calculaTotal(){    
      var colunas = document.querySelectorAll('#products-table tr td');
      var numColunas = colunas.length;
      for (let i=0; i<numColunas; i++){
         alert(colunas[i].textContent);    
      }
}
    
09.05.2017 / 02:15