0

I want to grab all the values from the label with class price and add them using jQuery. Now actual webpage is different but to understand the concept I am only putting minimum code here. There are 3 labels for prices, and 1 more for total:

<label class="price">120</label>
<label class="price">250</label>
<label class="price">342</label>
<label id="total"></label>

I read that .each() can be used but I could not understand how to use it for this purpose. I have uploaded jsfiddle over here http://jsfiddle.net/vivpad/cysjtrh8/1/

Vivek Padhye
  • 731
  • 3
  • 13
  • 26

5 Answers5

2

Basic example

jQuery(document).ready(function($){
    var total = 0;
    $('label.price').each(function(){
        var value = parseFloat($(this).text());
        total += value;
    });
    $('#total').text(total);
});

DEMO

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
2

You could get total price mapping .price elements text:

jQuery(document).ready(function ($) {
    $('#total').text(function () {
        return $('.price').map(function () {
            return +$(this).text()
        }).get().reduce(function (pv, cv) {
            return pv + cv;
        }, 0);
    });
});

-jsFiddle-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • interesting use of reduce. – Jai Nov 19 '15 at 11:57
  • 1
    @Jai From [there](http://stackoverflow.com/questions/3762589/fastest-javascript-summation) But that's not really optimized and not really readable. I find mohamed's answer better imho – A. Wolff Nov 19 '15 at 11:57
1

Note that you need to add jquery to your jsfiddle.

Also - you don't need to use .each - you can use arrays as well. Which simplifies it much and it is more efficient. See here: http://jsfiddle.net/vivpad/cysjtrh8/9

var sum = 0;
var prices = $("label.price");
for (var i = 0; i < prices.length; i++)
    sum += parseInt($(prices[i]).text());

$("#total").text(sum);
Igal S.
  • 13,146
  • 5
  • 30
  • 48
1

try this:

jQuery(document).ready(function($){
    var total = 0;
    $('.price').each(function() {
        var temp = $(this).html();
        total += parseFloat(temp);
    });
    $('#total').html(total);
});

JsFiddle

Apb
  • 979
  • 1
  • 8
  • 25
0

Try:

var labelvalues = $('label').map(function () {
     return $(this).text();
 }).get();
 var total = 0;
 for (var i = 0; i < labelvalues.length; i++) {
     total += labelvalues[i] << 0;
 }
 $("#total").text(total);

DEMO

Here I am using map function to translate all items to new array of items. And add the elements in the array.

Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97