Calculate sum with jQuery

Joined
Aug 21, 2023
Messages
40
Reaction score
0
Hi everyone,
I have a table row with book prices . Now I want to add jQuery code that calculates all the prices and displays it below. How can I do this?
 
Joined
Jul 4, 2023
Messages
479
Reaction score
60
Did you tried in that way?

[ full code on-line ]
JavaScript:
$(document).ready(function() {
  calculateTotalPrice();
});

function calculateTotalPrice() {
  let totalPrice = 0;
  $('#bookTable tbody tr').each(function() {
    let price = parseFloat($(this).find('.price').text());
    totalPrice += price;
  });

  $('#totalPrice').text(totalPrice.toFixed(2));
}
sample html code
HTML:
<style>
  thead th,
  tfoot td {
    background-color: hsl(0 0% 0% /.8);
    padding: .25rem;
    color: wheat;
  }
  tbody tr {
    cursor: default;
    transition: all 250ms;
  }
  tbody tr:nth-child(odd) {
    background-color: hsl(0 0% 0% /.2);
  }
  tbody tr:hover {
    background-color: hsl(0 0% 0% /.4);
    color: white;
  }
  td { 
    width: 6rem;
    text-align: center;
    padding: .15rem;
  }
  tfoot {
    font-weight: bold;
  }
  tfoot td:first-child {
    text-align: right;
  }
  .price {
    font-size: 95%;
  }
</style>

<table id="bookTable">
  <thead>
    <tr>
      <th>Title</th>
      <th>Author</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Book 1</td>
      <td>Author 1</td>
      <td class="price">10.99</td>
    </tr>
    <tr>
      <td>Book 2</td>
      <td>Author 2</td>
      <td class="price">15.00</td>
    </tr>
    <tr>
      <td>Book 3</td>
      <td>Author 3</td>
      <td class="price">20.53</td>
    </tr>
    <tr>
      <td>Book 4</td>
      <td>Author 4</td>
      <td class="price">12.02</td>
    </tr>    
  </tbody>
  <tfoot>
    <tr>
      <td colspan="2">Total Price</td>
      <td id="totalPrice">0.00</td>
    </tr>
  </tfoot>
</table>

or
[ full code on-line ]
JavaScript:
$(document).ready(function() {
  calculateTotalPrice();
});

function calculateTotalPrice() {
  let totalPrice = 0;
  $('#bookTable tbody .price').each(function() {
    totalPrice += parseFloat($(this).text());
  });

  $('#totalPrice').text(totalPrice.toFixed(2));
}
 
Joined
Aug 21, 2023
Messages
40
Reaction score
0
This code doesn't work right now.I suppose i have to change something. This is part of the html I have:
HTML:
<div id="container">
      <h1>Chapter 12</h1>
      <table id="t-1" class="sortable">
        <thead>
          <tr>
            <th></th>
            <th class="sort-alpha">Title</th>
            <th class="sort-alpha">Author(s)</th>
            <th class="sort-date">Publish Date</th>
            <th class="sort-numeric">Price</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td><img src="images/2862_OS.jpg" alt="Drupal 7"></td>
            <td>Drupal 7</td>
            <td>David <span class="sort-key">Mercer</span></td>
            <td>September 2010</td>
            <td>$44.99</td>
          </tr>
          <tr>
            <td>
              <img src="images/3685EN_Amazon%20SimpleDB_LITE_0.jpg" alt="Amazon SimpleDB: LITE">
            </td>
            <td>Amazon SimpleDB: LITE</td>
            <td>Prabhakar <span class="sort-key">Chaganti</span>, Rich Helms</td>
            <td>May 2011</td>
            <td>$9.99
            </td>
          </tr>
          </tbody>
    </table>
</div>
...
 
Joined
Jul 4, 2023
Messages
479
Reaction score
60
I suppose i have to change something
Yes, you need to adapt the code a bit to your html code.

JavaScript:
function calculateTotalPrice() {
  const totalPrice = [...$('#t-1 tbody td:last-child')].reduce((s, e) => {
    return s + parseFloat($(e).text().slice(1));
  }, 0);

  $('#t-1 #totalPrice').text('$' + totalPrice.toFixed(2));
}

Example using the reduce function
[ full code on-line ]
HTML:
<style>
  thead th,
  tfoot td {
    background-color: hsl(0 0% 0% /.8);
    padding: .25rem;
    color: wheat;
  }
  tbody tr {
    cursor: default;
    transition: all 250ms;
  }
  tbody tr:nth-child(odd) {
    background-color: hsl(0 0% 0% /.2);
  }
  tbody tr:hover {
    background-color: hsl(0 0% 0% /.4);
    color: white;
  }
  td {
    width: 6rem;
    text-align: center;
    padding: .15rem;
  }
  tfoot {
    font-weight: bold;
  }
  tfoot td:first-child {
    text-align: right;
  }
  .price {
    font-size: 95%;
  }
  tbody td:last-child {
    color: red;
  }
</style>

<div id="container">
  <h1>Chapter 12</h1>
  <table id="t-1" class="sortable">
    <thead>
      <tr>
        <th></th>
        <th class="sort-alpha">Title</th>
        <th class="sort-alpha">Author(s)</th>
        <th class="sort-date">Publish Date</th>
        <th class="sort-numeric">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><img src="images/2862_OS.jpg" alt="Drupal 7"></td>
        <td>Drupal 7</td>
        <td>David <span class="sort-key">Mercer</span></td>
        <td>September 2010</td>
        <td>$44.99</td>
      </tr>
      <tr>
        <td>
          <img src="images/3685EN_Amazon%20SimpleDB_LITE_0.jpg" alt="Amazon SimpleDB: LITE">
        </td>
        <td>Amazon SimpleDB: LITE</td>
        <td>Prabhakar <span class="sort-key">Chaganti</span>, Rich Helms</td>
        <td>May 2011</td>
        <td>$9.99</td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td colspan="4">Total Price</td>
        <td id="totalPrice">0.00</td>
      </tr>
    </tfoot>
  </table>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    calculateTotalPrice();
  });

  function calculateTotalPrice() {
    const totalPrice = [...$('#t-1 tbody td:last-child')].reduce((s, e) => {
      return s + parseFloat($(e).text().slice(1));
    }, 0);

    $('#t-1 #totalPrice').text('$' + totalPrice.toFixed(2));
  }
</script>
 
Last edited:
Joined
Aug 21, 2023
Messages
40
Reaction score
0
Yes, you need to adapt the code a bit to your html code.

JavaScript:
function calculateTotalPrice() {
  const totalPrice = [...$('#t-1 tbody td:last-child')].reduce((s, e) => {
    return s + parseFloat($(e).text().slice(1));
  }, 0);

  $('#t-1 #totalPrice').text('$' + totalPrice.toFixed(2));
}

Example using the reduce function
[ full code on-line ]
HTML:
<style>
  thead th,
  tfoot td {
    background-color: hsl(0 0% 0% /.8);
    padding: .25rem;
    color: wheat;
  }
  tbody tr {
    cursor: default;
    transition: all 250ms;
  }
  tbody tr:nth-child(odd) {
    background-color: hsl(0 0% 0% /.2);
  }
  tbody tr:hover {
    background-color: hsl(0 0% 0% /.4);
    color: white;
  }
  td {
    width: 6rem;
    text-align: center;
    padding: .15rem;
  }
  tfoot {
    font-weight: bold;
  }
  tfoot td:first-child {
    text-align: right;
  }
  .price {
    font-size: 95%;
  }
  tbody td:last-child {
    color: red;
  }
</style>

<div id="container">
  <h1>Chapter 12</h1>
  <table id="t-1" class="sortable">
    <thead>
      <tr>
        <th></th>
        <th class="sort-alpha">Title</th>
        <th class="sort-alpha">Author(s)</th>
        <th class="sort-date">Publish Date</th>
        <th class="sort-numeric">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><img src="images/2862_OS.jpg" alt="Drupal 7"></td>
        <td>Drupal 7</td>
        <td>David <span class="sort-key">Mercer</span></td>
        <td>September 2010</td>
        <td>$44.99</td>
      </tr>
      <tr>
        <td>
          <img src="images/3685EN_Amazon%20SimpleDB_LITE_0.jpg" alt="Amazon SimpleDB: LITE">
        </td>
        <td>Amazon SimpleDB: LITE</td>
        <td>Prabhakar <span class="sort-key">Chaganti</span>, Rich Helms</td>
        <td>May 2011</td>
        <td>$9.99
        </td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td colspan="4">Total Price</td>
        <td id="totalPrice">0.00</td>
      </tr>
    </tfoot>
  </table>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    calculateTotalPrice();
  });

  function calculateTotalPrice() {
    const totalPrice = [...$('#t-1 tbody td:last-child')].reduce((s, e) => {
      return s + parseFloat($(e).text().slice(1));
    }, 0);

    $('#t-1 #totalPrice').text('$' + totalPrice.toFixed(2));
  }
</script>
This code is better but instead of the price sum I get the code $NaN .
 
Joined
Jul 4, 2023
Messages
479
Reaction score
60
This code is better but instead of the price sum I get the code $NaN .
My example works ... on-line ;)

1699032613541.png
 
Joined
Jul 4, 2023
Messages
479
Reaction score
60
Joined
Aug 21, 2023
Messages
40
Reaction score
0
Now with a few cosmetic changes... it works fine on-line
JavaScript:
function calculateTotalPrice() {
  for (let id=1; id<=3; id++) {
    const totalPrice = [...$('#t-' + id + ' tbody td:last-child')].reduce((s, e) => {
      return s + parseFloat($(e).text().trim().slice(1));
    }, 0);

    $('#t-' + id + ' #totalPrice').text('$' + totalPrice.toFixed(2));
  }
}
This code works online but I still get the result 0.00$ on my comp even with localhost xampp. I don't know what's the problem but I hope I'll figure it out. Thanks.
 
Joined
Aug 21, 2023
Messages
40
Reaction score
0
Now with a few cosmetic changes... it works fine on-line
JavaScript:
function calculateTotalPrice() {
  for (let id=1; id<=3; id++) {
    const totalPrice = [...$('#t-' + id + ' tbody td:last-child')].reduce((s, e) => {
      return s + parseFloat($(e).text().trim().slice(1));
    }, 0);

    $('#t-' + id + ' #totalPrice').text('$' + totalPrice.toFixed(2));
  }
}
Ok i copy pasted the code from online editor so it works fine. What did you change?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top