joergi1988
joergi1988

Reputation: 73

Sum Quantity and Price in Tables

I have 4-5 dynamically created Tables with PHP

<table class="table11">
  <tbody>
    <tr>
      <td>Name</td>
      <td class="quantity">2</td>
      <td class="price">20</td>
      <td class="sum_one">40</td>
    </tr>
    <tr>
      <td>Name</td>
      <td class="quantity">1</td>
      <td class="price">30</td>
      <td class="sum_one">30</td>
    </tr>
    <tr>
      <td></td>
      <td class="total_quantity">3</td>
      <td></td>
      <td class="total_sum">70</td>
    </tr>
  </tbody>
</table>

<table class="table11">
  <tbody>
    <tr>
      <td>Name</td>
      <td class="quantity">1</td>
      <td class="price">10</td>
      <td class="sum_one">10</td>
    </tr>
    <tr>
      <td>Name</td>
      <td class="quantity">2</td>
      <td class="price">10</td>
      <td class="sum_one">20</td>
    </tr>
    <tr>
      <td></td>
      <td class="total_quantity">3</td>
      <td></td>
      <td class="total_sum">30</td>
    </tr>
  </tbody>
</table>

I would like to sum all prices in the table and show in total_sum.

I have tried this:

var sum = 0;
var quantity = 0;
var sum1 = 0;
$('.price').each(function() {
    var price = $(this);
    var q = price.closest('tr').find('.quantity').html();
    sum += parseInt(price.html()) * parseInt(q);
    quantity += parseInt(q);
    sum1 = 0;
    sum1 += parseInt(price.html()) * parseInt(q);
    price.closest('tr').find('.sum_one').html(sum1);
});

console.log(sum);

$('table.table11 tr:last-child').find('.total_sum').html(sum);

Which doesn't work, in the console it logs the sum, that is correct but in the tables it doesn't change.

How can I update the sums in each of the Tables with the relevant sum of price?

As I dynamically delete rows I would like the totals to update accordingly.

https://jsfiddle.net/qfjes1zj/ .... i will all sum table by table and not complete sum at end. every table sum.

Upvotes: 0

Views: 694

Answers (2)

Luca De Nardi
Luca De Nardi

Reputation: 2321

Why is the td called total_sum

<td class="total_sum">30</td>

and then you update total-price?

$('table.table11 tr:last-child').find('.total_price').html(sum);

It should be just

$('.total_sum').html(sum);

Upvotes: 1

Igino Boffa
Igino Boffa

Reputation: 451

try:

$(document).ready( function(){
    var sum = 0;
var quantity = 0;
var sum1 = 0;
$('.price').each(function() {
    var price = $(this);
    var q = price.closest('tr').find('.quantity').html();
    sum += parseInt(price.html()) * parseInt(q);
    quantity += parseInt(q);
    sum1 = 0;
    sum1 += parseInt(price.html()) * parseInt(q);
    price.closest('tr').find('.sum_id').html(sum1);
});



$('table.table11 tr:last-child').find('.total_price').html(sum);
});

Calculation should be executed after page has been loaded

Upvotes: 0

Related Questions