Utilizing jQuery for Summation Calculation

How can I use jQuery to calculate the total sum of prices for all products in a table with the column name "price"? Once calculated, how do I store this sum in a variable?

<table id ="tab">
    <th>Product</th><th>Price</th>
    <tr><td>A</td><td>752</td></tr>
    <tr><td>B</td><td>652</td></tr>
    <tr><td>C</td><td>1000</td></tr>
</table>

Answer №1

What do you think about this solution?

$(document).ready(function() {
  var total = 0;
  $('#tab tr td:nth-of-type(2)').each(function(i, cell) {
    total += parseInt($(cell).text(),10);
  });
  console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table id="tab">
  <th>Product</th>
  <th>Price</th>
  <tr>
    <td>A</td>
    <td>752</td>
  </tr>
  <tr>
    <td>B</td>
    <td>652</td>
  </tr>
  <tr>
    <td>C</td>
    <td>1000</td>
  </tr>
</table>

Answer №2

employ this

<script>
    let total=0;
    $('#table').find('tr').each(function(index,value){
       total+=parseInt($(this).find('td').eq(1).text());
    })
    alert(total);
</script>

Answer №3

$(document).ready(function(){
   var total = 0;
   $('tr td:nth-child(2)').each(function(){
 total+=parseInt($(this).text());
   })
   alert(total);
})
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<table id ="tab">
    <th>Product</th><th>Price</th>
    <tr><td>A</td><td>752</td></tr>
    <tr><td>B</td><td>652</td></tr>
    <tr><td>C</td><td>1000</td></tr>
</table>

Answer №4

How to use map() and reduce() in a single line of code

var sum = $('tr td:nth-child(2)')
  .map((_, el) => +$(el).text().trim() || 0).get()
  .reduce((a, c) => a + c);
  
console.log('Total Sum:', sum)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tab">
  <th>Product</th>
  <th>Price</th>
  <tr>
    <td>A</td>
    <td>752</td>
  </tr>
  <tr>
    <td>B</td>
    <td>652</td>
  </tr>
  <tr>
    <td>C</td>
    <td>1000</td>
  </tr>
</table>

Answer №5

If the price you are looking for is located in the last element of every tr, you can use the following code:

var total = 0;

$('#tab tr td:last-child').each(function(index) {
  total = total + parseInt($(this).text());
});

alert(total);

See a demo here: https://jsfiddle.net/uwhLjwce/

Answer №6

Here is a suggested approach for you to try:

function calculateTotal() {
    var totalPrice = 0;
    var prices = $("#table tr td:nth-child(2)");
    var textValue;
    var numericValue;

    for (var j = 0, length = prices.length; j < length; j++) {
        textValue = $(prices[j]).text();
        numericValue = parseInt(textValue, 10);
        totalPrice += numericValue;
    }

    return totalPrice;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The module 'cropit' is not located within Npm's directory

I'm having trouble with npm recognizing my installation of cropit. In my package.json, I have specified the following lines: "cropit": "^0.1.9", "jquery": "~2.1.1" Could it be that I selected the wrong version? Do the versions of jquery and cropit I ...

Navigating through JSON Serialization in Django and Unpacking JSON Data in Jquery

So here's the code snippet that I'm currently working with: def success_comment_post(request): if "c" in request.GET: c_id = request.GET["c"] comment = Comment.objects.get(pk=c_id) model = serializers.serialize("json" ...

What are some ways I can enhance the typography within Material UI?

Currently, I am in the process of developing a custom theme utilizing createMuiTheme. However, my application requires more typography variants than what Material UI provides out of the box. I need to extend the typography so that it aligns with my specifi ...

Ways to limit the width of content

While I could use a div container to solve this issue, I'm exploring the possibility of achieving it without one. My goal is to create a layout that is flexible between 640px and 1280px, but remains fixed beyond that range. The colored div I have cur ...

The radio button element could not be located using the attribute "checked="Checked""

While working with Geb, I encountered an issue using the code div.find("input","checked":contains("checked")). This is the snippet of code I attempted to use in order to locate the checked radio button on a webpage. However, I received an error when using ...

It's proving difficult for me to align my header and navbar on the same line

Recently, I've delved into the world of HTML/CSS and encountered a challenge. My goal is to align my header (containing an h1 tag) and navbar on the same line. Ideally, the header should float left with the navbar positioned closely to its left. Howev ...

CSS: Adding decorative trailing dots below the header when positioned over a background

I am seeking assistance with achieving a specific effect in CSS, as shown in the attached screenshot. The trailing dots should cover the entire width of the element (100%) and be responsive. However, I encountered an issue when placing the header on a bac ...

Problems with Key Presses in Form Verification

Yesterday evening, our supervisor called me to report an issue with our app. He mentioned that when he tried to log in using a dummy password, the validation was successful. It seems that clicking on the mouse to authenticate the password was working corr ...

Enhancing text display and spacing in Safari versions 5 to 6, as well as Chrome

After creating an introductory animation using jquery, I noticed that it displays correctly on my machine in Firefox, Chrome, and Safari. However, when viewing it on the client's devices, the animation is not working properly. The client provided a s ...

The functions `jQuery .each()` and `jQuery .post()` offer powerful capabilities

For the past day, I've been working hard to make this method function properly. My goal is to utilize the jQuery .each() function to execute a task for each element within a specific array. The array is generated from a .post() request. $(document) ...

I'm baffled by this unsemantic grid - why is the final div getting pushed below the rest?

I am working with the unsemantic fluid grid system and aiming to create a row of divs that are all in line and together cover 100% of the page. <div class="grid-container"> <div class="grid-parent yy name-strip zz"> <div class="yello ...

Hide overflow for images with unique shapes

Here are the two image layers: One shows a hand holding a phone, and the other is a black hole. This is how you can achieve it using HTML markup: <div class="wrapper"> <img class="wrapper__image" src="path/to/image.png"> </div> And ...

When jQuery's fadeOut function is used with a callback, two elements appear simultaneously when the action is performed quickly

This problem seems straightforward, but I've hit a roadblock. Here's the code snippet in question: When I quickly move through all the elements, both p.hidden and form remain visible despite the intended behavior. I attempted to include stop ...

Why isn't cancelAll function available within the onComplete callback of Fine Uploader?

This is the completion of my task. $('#fine-uploader-house').fineUploader({ ... }).on('complete', function(event, id, name, jsonData) { if(!checkEmpty(jsonData.cancelAll) && jsonData.cancelAll){ //$(this).cancelAll(); ...

The data retrieved by the $.getJSON method is not displaying as a line graph

I am currently dealing with two files searh_journal.php <script type="text/javascript"> function submitForm() { var form = document.myform; var dataString = $(form).serialize(); $.ajax({ type: 'POST', url: & ...

Modify the navbar background color in bootstrap-vuejs

As per the information provided in the documentation, the instructions for setting styles for the navigation bar are as follows: <b-navbar toggleable="lg" type="dark" variant="info"> <!-- Or --> <b-navbar toggleable="lg" type="dark" variant ...

Woocommerce Dual Column Payment Portal

I prefer a two-column layout for the checkout process on www.narwal.shop/checkout Here is the code I added: /* Large devices (large desktops, 1200px and up) */ @media (min-width: 993px) { /* --------------------- WOOCOMMERCE -------- ...

I am experiencing issues with the functionality of the Search Button in my code

I am experiencing an issue with the Search Button in my Search Form. I created the Search form using only html and pure CSS to test whether JS is necessary for a Search form with Drop Down Filter! Do I need to incorporate some JS code or is it feasible to ...

Having trouble eliminating the underline on Vue router-link?

I've experimented with various approaches in an attempt to remove the underline from router-link. This is the code I have: <router-link :to="{name: 'Plan'}"> <div>Plan Your Trip</div> <div class=&apos ...

Troublesome Display of Badges in Bootstrap 5

My goal is to include a badge on a label, however all it does is change the text color to white <asp:Label CssClass="badge badge-pill badge-success" ID="Label1" runat="server" Text="Label"></asp:Label> ...