1

I can get the sum of a certain value in a table bay using this code..

 $(calculateSum);

 function calculateSum() {

 var sum = 0;
//iterate through each td based on class and add the values
 $(".d").each(function() {
    var value = $(this).text();
    //add only if the value is number
    if(!isNaN(value) && value.length!=0) {
        sum += parseFloat(value);
    }

 });
$('#result').text(sum);    
};

And my table Have Value 12

Now,I have 5 tables in a html and each table has a td element which values differs from each other,Whats the best way to get those values in javascript?

6
  • do you want all td's values in one collection? Commented Jul 2, 2014 at 4:44
  • get the tables first, then use .find to get the inner tds Commented Jul 2, 2014 at 4:47
  • @Mritunjay Yes,and I want only specific td's that I want to get a values<td class="d"></td> Commented Jul 2, 2014 at 4:49
  • @Fabricator,can you show me some example on how to do that in javascript? Commented Jul 2, 2014 at 4:50
  • I want to get value in every table, I can do that by copying the javascript code in each table.So table 1 has value 12,table 2 has value 14.....What I mean is the javascript code is written in every table to get the value on each table.Is there's any better ways to write javascript code only once?Because those tables are in the same template/html Commented Jul 2, 2014 at 4:56

1 Answer 1

2

Iterate over each table, and use .find to get descendant tds.

$('table').each(function(i, table) {
  var sum = 0;
  $(table).find('.d').each(function() {
    ..
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.