How to calculate the total value in a dynamically created table?

Asked

Viewed 179 times

1

I have the following code that creates a table in jquery. The problem is that I wanted to create a subtotal that would add up all the values of the total column. But I’m not getting it because the table is created dynamically. Any suggestions?

Follows the code:

function retorna_pedidos(valor)
{
 let mensagem_pedidos = "Nenhum pedido encontrado";
 let container_mostra_pedidos = $('.mostra_pedidos');
 let quantidade = $('#qtd').val();
 let quantidade_pedidos = "";
 let valorTotal = "";
 let itemHTMLp = "";

 if (valor == null)
 {
   valor = 1;
  }

 $.ajax({
  url: url_base + "pedidos?qtd=" + quantidade + "&page=" + valor,
  type: 'GET',
  dataType: 'json',
  success: function (data)
  {
  var retorno = data.pedidos.data;
  if (retorno == 0)
  {
    $('.classe-pedidos').css('display','none');
    $('.pedido-error-registro').css('display','block');
    $('.pedido-error-registro .mensagem-erro').html(mensagem_pedidos);
  }
  else
  {

    $.each(data, function(key,item) {

      let registros  = item.data.length;
      let current_page = item.current_page;
      let last_page = item.last_page;
      let next_page_url = item.next_page_url;
      let prev_page_url = item.prev_page_url;
      let pedidos = item.data;

      sessionStorage.setItem('pagina',current_page);
      sessionStorage.setItem('last_page',last_page);

      if (next_page_url == null)
      {
        if (current_page == 1)
        {
          $('.action-bar-pedido').html("<a id='btn-pagina-anterior-pedido' title='Pàgina Anterior' class='buttonPrevious btn btn-primary' style='display: none;'><< Página Anterior</a>");
        }
        else
        {
          $('.action-bar-pedido').html("<a id='btn-pagina-anterior-pedido' title='Pàgina Anterior' class='buttonPrevious btn btn-primary' style='display: block;'><< Página Anterior</a>");
        }
      }
      else if (prev_page_url == null)
      {
        $('.action-bar-pedido').html("<a id='btn-proxima-pagina-pedido' title='Próxima Página' display='block' class='buttonNext btn btn-success'>Próxima Página >></a>");
      }
      else if (prev_page_url != null || next_page_url != null)
      {
        $('.action-bar-pedido').html("<a id='btn-proxima-pagina-pedido' title='Próxima Página' display='block' class='buttonNext btn btn-success'>Próxima Página >></a><a id='btn-pagina-anterior-pedido' title='Pàgina Anterior' class='buttonPrevious btn btn-primary' style='display: block;'><< Página Anterior</a>");
      }

      for (var i in pedidos) {
        id_pedido = pedidos[i].pedidos_id;
        nome_cliente = pedidos[i].nome_cliente;
        nome_produto = pedidos[i].nome_produto;
        data_atual = pedidos[i].data;
        data_pedido = data_atual.split("-").reverse().join("/");
        frete_atual = pedidos[i].frete;
        preco_produto = pedidos[i].preco_produto;
        quantidade_pedidos = pedidos.length;
      //  console.log(pedidos);

        valorTotal =  parseFloat(quantidade_pedidos) * parseFloat(preco_produto) + frete_atual;

        itemHTMLp += "<tr>";
        itemHTMLp += "<td><input type='checkbox' value='" +  id_pedido + "' name='verifica_check_box[]' id='verifica_check_box' class='flat'/></td>";
        itemHTMLp += "<td>" + nome_cliente + "</td>";
        itemHTMLp += "<td>" + nome_produto + "</td>";
        itemHTMLp += "<td>" + data_pedido + "</td>";
        itemHTMLp += "<td class='frete-produto'>" + frete_atual + "</td>";
        itemHTMLp += "<td class='preco-produto'>" + preco_produto + "</td>";
        itemHTMLp += "<td class='valor-total'>" + valorTotal + "</td>";
        itemHTMLp += "</tr>";
      }
    });
    container_mostra_pedidos.html(itemHTMLp);
  }

},
error: function (data)
{
  console.log(data);
}
});
  • Is your doubt about how to generate the total or when to do it? If you make a function that calculates the total and calls it after playing the table in the DOM effectively, you will have what you want. Would that be your problem or would it be in the same sum function?

  • in fact it would add the values of td value-total. That neither product 1 = 25, product 2 = 50, total = 75

  • @Diegosantos. It would only add the values of the total-value column, because it already makes the sum of the product in the variable valueTotal

  • Brother, your code has some key error. Can you post it again fixed? Then I help you blz...

  • I tried to run it but it already gave problem in the interpretation...

  • OK @Diegosantos. I’ve got it

Show 1 more comment

2 answers

0

It is not the same as yours, as I do not have your data I can not simulate. But follows...

$(function(){
var total = 0;
$('.valor-total').each(function () {
    total += parseInt($(this).text());
});

console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<table>
  <tr>
    <td class='valor-total'>1<td>
    <td class='valor-total'>15<td>
    <td>abc<td>
    <td class='valor-total'>22<td>
    <td >def<td>
  </tr>
</table>

  • It worked. Only there’s a problem with paging. It takes the totals of each page. Hence I can add them all up?

  • Hummm ai complicates a little more. But are you sure you need to do this? If the user accounts for his total he will find that he has error in the page pq does not match the information displayed, no? But if necessary, it would be more interesting to go back to this information from the server or have access to the total already calculated. You probably page your query, correct?

  • But worse than it has no way to do so...kkk. Could not calculate this total before or return the value of each product of the loop and already calculate it?

  • There are many variables to consider... For example, what is the return you get from the server. What information is in it, you know? If you return all possible and imaginable results in this return it is possible to add, however, I do not indicate in any way, because of performance and because you do not know the client machine you are accessing, understand? The simplest way to solve it is with another request or if it is returned in json for example, creates an attribute in it already with the added value and only takes it in json. How about this way?

  • You don’t want the values to come from all pages of the right pagination ?

0

You can calculate all values of td going through each one with .each() and adding the values. Calling the function below you get the total result:

function total(){
   tt_final = 0;
   subs = $('.valor-total');
   
   subs.each(function(){
      tt_final += parseFloat($(this).text());
   });
   
   alert(tt_final);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
   <tr>
      <td class="valor-total">
         10
      </td>
   </tr>
   <tr>
      <td class="valor-total">
         4
      </td>
   </tr>
   <tr>
      <td class="valor-total">
         50
      </td>
   </tr>
</table>
<br /><br />
<input type="button" value="Calcular" onclick="total()" />

Remarks:

1. Optimize your code by concatenating the table code in this way:

itemHTMLp += "<tr>"
+"<td><input type='checkbox' value='1' name='verifica_check_box[]' id='verifica_check_box' class='flat'/></td>"
+"<td>fulano</td>"
+"<td>produto</td>"
+"<td>14/11/2017</td>"
+"<td class='frete-produto'>0</td>"
+"<td class='preco-produto'>5</td>"
+"<td class='valor-total'>31</td>"
+"</tr>";

2. Failed to open and close the table with <table> and </table>:

You can do it like this: container_mostra_pedidos.html('<table>'+itemHTMLp+'</table>');

  • thanks, but the container_mostra_pedidos is already a variable with table.

Browser other questions tagged

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