I want to get the total and a average from a number of rides. Now i'm Stuck with this now the whole day, first i tried it with span's around it but i thought maybe with a array is better, hope somebody can help me with the missing piece.
Example: http://jsbin.com/inapey/31/edit
<tbody id="rides">
 <tr>
 <td class="muted"><small>Mr.</small></td>
 <td>John</td>
 <td>Smith</td>
 <!-- Every ride of this person -->
 <td class="ride_km" style="display:none;">225,75</td>
 <!-- Sum & Average of this person -->
 <td class="ride_total_km"></td>
 <td class="ride_average_km"></td>
 </tr>
 <tr>
 <td class="muted"><small>Mrs.</small></td>
 <td>Jane</td>
 <td>Smith</td>
 <!-- Every ride of this person -->
 <td class="ride_km" style="display:none;">150,300</td>
 <!-- Sum & Average of this person -->
 <td class="ride_total_km"></td>
 <td class="ride_average_km"></td>
 </tr>
 </tbody>
jquery
$(document).ready(function(){
 var total = 0;
 $('#rides tr').each(function() {
 var RidesKM = $(this).fin('.ride_km').html().split(","); 
 var arr = jQuery.makeArray(RidesKM); 
 alert(arr);
 var SumKM = ???;
 var AveKM = ???; 
 /* Total KM's */
 $(this).find('.ride_total_km').html(SumKM);
 /* Average KM's */
 $(this).find('.ride_average_km').html(AveKM.toFixed(0)); 
 }); 
});
 - 
 Woh, I just realized something, the ',' is a delimiter for every value. I thought it was the decimal seperator (in French we use a comma not a period).VVV– VVV2013年02月21日 14:26:34 +00:00Commented Feb 21, 2013 at 14:26
 
2 Answers 2
*Updated answer.
Here's the code:
$(document).ready(function () {
 $('#rides tr').each(function () {
 var that = $(this);
 var sum = 0;
 that.find('.ride_km').each(function () {
 var values = $(this).text().split(',');
 $.each(values,function() {
 sum += parseFloat(this);
 });
 /* Total KM's */
 that.find('.ride_total_km').html(sum.toFixed(2));
 /* Average KM's */
 that.find('.ride_average_km').html((sum / values.length).toFixed(2))
 });
 });
});
It's weird though that you store the values in a hidden td. I would suggest (if you could do all the calculations in javascript or if possible from the server (if you're using something like PHP or other).
1 Comment
If I'm understanding correctly, you want the total for each person. In this case, you don't need the total variable:
$(document).ready(function(){
 $('#rides tr').each(function() {
 var SumKM = 0;
 var RidesKM = $(this).find('.ride_km').html().split(",");
 for (i = 0; i < RidesKM.length; i++) {
 SumKM += parseInt(RidesKM[i]);
 }
 var AveKM = SumKM / RidesKM.length; 
 /* Total KM's */
 $(this).find('.ride_total_km').html(SumKM);
 /* Average KM's */
 $(this).find('.ride_average_km').html(AveKM.toFixed(0)); 
 }); 
});