Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

jQuery: Sum multiple values

Featured Replies

This should be pretty basic, but I can't seem to get it right :D I am trying to sum multiple dynamic values and output the total for each parent div.

 

My html is as the example below:

<div class="parent">
    <ul>
        <li><span class="count">0</span></li>
        <li><span class="count">1</span></li>
        <li><span class="count">4</span></li>
        <li><span class="count">0</span></li>
    </ul>
    <span class="total">0</span>
</div>
<div class="parent">
    <ul>
        <li><span class="count">1</span></li>
        <li><span class="count">3</span></li>
        <li><span class="count">0</span></li>
        <li><span class="count">2</span></li>
   </ul>
   <span class="total">0</span>
</div>

JS:

$('.parent').each(function(){
	var sum = 0;
        var count = $(this).find('.count').text();
	sum = +Number(count);
        $(this).find('.total').text(sum);
	console.log(sum)
});

How do I iterate through each span.count and get its value? Hope that makes sense - thank you very much in advance! :)

Edited by teodora

Try this: http://jsfiddle.net/ux0o8gqu/

$('.parent').each(function(){	
    var sum = 0;
    var counts = $(this).find('.count');
    
    counts.each(function() {
        sum+= parseInt($(this).text());
    });  
    console.log(sum);  
});

Edit: Forgot to add code!

Edited by Lyndsey

This is the JavaScript jQuery you need:

 

The .text function returns the result as a string so it needs to be converted to a number though the parseInt function.

You also want to be looping through each individual count within the parent each loop, and incrementing the sum on each iteration.

$('.parent').each(function(){
    var sum = 0;
    $(this).find('.count').each(function(){
        sum += parseInt($(this).text());
    });
    console.log(sum);
	
});

Edit Lyndseys result posted while I was writing mine is pretty much the same :)

Edited by rbrtsmith

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.