Sum values of a TD with Avascript

Asked

Viewed 3,154 times

0

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

Follows 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 go through the table and get the column value 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);
  };
 }
  • Which of the columns you want to add?

2 answers

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);    
      }
}

0


Your attempt to mix jQuery with Javascript vanilla Just to select elements of the DOM became very strange. It works, but there is no reason to do it, it leaves the code inconsistent. If you’re using jQuery, take advantage of its features, since you want to manipulate the DOM and that’s exactly what it was created for.

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

Take 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>
<table id="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 function getTotal whenever necessary.

  • 1

    This story of "mixing jQuery with javascript" always sounds strange to me; jQuery is javascript, using some objects defined in a library. It would be better to say "mixing jQuery with direct DOM manipulation" (Document Object Model, the API that browsers expose to manipulate a page via script).

  • @Wtrmute in fact, would be more accurate to say this, but the idea I wanted to pass was clear. The fact of using $("#x") in a row and getElementByTagName("tr") otherwise leaves the code rather inconsistent and should be avoided doing. Anyway, I will edit the answer to make the change.

  • 1

    I do not disagree that it is necessary to avoid (although by 2007 there were those who recommended to use document.getElementById('foo') instead of $('#foo') for efficiency reasons), but we must avoid propagating the misunderstanding that jQuery is not javascript. You know it is, I know it is, but not every 17-year-old starting programming who will read this question three years from now will know, and may end up learning something wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.