Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum using jQuery each function without global variable

Tags:

jquery

each

I want to add some HTML elements that have the same class name.

So, the code will be like this with jQuery.

$(".force").each(function (){
    a += parseInt( $(this).html());
});
$("#total_forces").html(a);

In this code, the variable has to be global.

Is there any other elegant way to sum every .force value and get the sum out of the each function without global variable?

like image 215
Jinbom Heo Avatar asked Nov 29 '22 10:11

Jinbom Heo


1 Answers

If you don't want to introduce a global variable, you could use something like this:

$("#total_forces").html(function() {
    var a = 0;
    $(".force").each(function() {
        a += parseInt($(this).html());
    });
    return a;
});
like image 120
Spiny Norman Avatar answered Nov 30 '22 23:11

Spiny Norman