Richard Bustos Richard Bustos - 3 years ago 382
HTML Question

Creating a sum of values in a table using javascript

Looking to replace all the "?" in the table below with the expected values.

Should I just add classes to the

<th>
that has a value in them and add them?

<table id="repair-invoice">
<tr>
<th>Item</th>
<th>Parts</th>
<th>Labor</th>
<th>Total</th>
</tr>
<tr>
<td>Automatic Transmission Replacement</td>
<td>$1,809.99</td>
<td>$830.00</td>
<td>?</td>
</tr>
<tr>
<td>Exhaust system replace</td>
<td>$279.99</td>
<td>$225.00</td>
<td>?</td>
</tr>
<tr>
<td>Replace air filter</td>
<td>$9.99</td>
<td>$0.00</td>
<td>?</td>
</tr>
<tr>
<td colspan="3">Total</td>
<td>?</td>
</tr>
</table>

Answer Source

You can iterate over the row/column combination and sum of the values like

var sum = 0;
$('#repair-invoice tr').slice(1, -1).each(function() {
  var $tr = $(this),
    total = 0;
  $tr.find('td').slice(1, -1).each(function() {
    total += +$(this).text().replace(/\$|,/g, '') || 0;
  });
  $tr.find('td:last-child').text(total);
  sum += total;
});
$('#repair-invoice tr:last-child td:last-child').text(sum.toFixed(2)); //will have to format and display the value
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="repair-invoice">
  <tr>
    <th>Item</th>
    <th>Parts</th>
    <th>Labor</th>
    <th>Total</th>
  </tr>
  <tr>
    <td>Automatic Transmission Replacement</td>
    <td>$1,809.99</td>
    <td>$830.00</td>
    <td>?</td>
  </tr>
  <tr>
    <td>Exhaust system replace</td>
    <td>$279.99</td>
    <td>$225.00</td>
    <td>?</td>
  </tr>
  <tr>
    <td>Replace air filter</td>
    <td>$9.99</td>
    <td>$0.00</td>
    <td>?</td>
  </tr>
  <tr>
    <td colspan="3">Total</td>
    <td>?</td>
  </tr>
</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download