1

Is it possible to add different numbers inside one variable?

Example:

$( ".list .task" ).each( function( ){ 
  var GetScore = $( this ).text();
  console.log(GetScore);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 
 <div class="list">
  <div class="task">1</div>
</div>
<div class="list">
  <div class="task">2.2</div>
</div>
<div class="list">
  <div class="task">4</div>
</div>
<div class="list">
  <div class="task">9.3</div>
</div>

Like this way I get the numbers in one variable, but how can I add them now? Or is it necessary to make a variable for every ".task" number?

Azametzin
  • 5,223
  • 12
  • 28
  • 46
Pepe
  • 960
  • 9
  • 21
  • Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Azametzin Mar 07 '20 at 15:09
  • @Azametzin Thx for the tip / link, I will take a look. – Pepe Mar 07 '20 at 15:14
  • @Azametzin I think your link only works with [arrays]. – Pepe Mar 07 '20 at 16:30

2 Answers2

4

First, you declare a variable for the initial value.
Then inside the function, you add to this value each number if it exists.

var GetScore = 0; // initial value

$( ".list .task" ).each( function(){    
    GetScore += parseFloat($(this).text()) || 0;
});

console.log(GetScore); // 16.5
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list">
  <div class="task">1</div>
</div>
<div class="list">
  <div class="task">2.2</div>
</div>
<div class="list">
  <div class="task">4</div>
</div>
<div class="list">
  <div class="task">9.3</div>
</div>
Azametzin
  • 5,223
  • 12
  • 28
  • 46
1

Please read about JavaScript Arrays. Alternative and better practice for your needs - create a variable and name it like total, initiate it with the value of 0. Then for every jQuery.each loop, add the element's value to the total variable. For example:

var total = 0;

$( ".list .task" ).each( function(){    
    total += parseInt($( this ).text());
});

console.log(total);
TamirNahum
  • 484
  • 2
  • 8
  • Hm, its not working for me - I have to fgure out why ... but thx for the tip / link. – Pepe Mar 07 '20 at 15:09
  • Please try using the `innerHTML` function instead of the `text` function. – TamirNahum Mar 07 '20 at 15:10
  • Now its working, but as info, you have some fails in your script. And at the end, with this way I also get only every number, not the sum. – Pepe Mar 07 '20 at 16:27