Connecting Tech Pros Worldwide Help | Site Map

function for Calculating sum of values in row and coloms of html table by javascript

Member
 
Join Date: Sep 2009
Location: London
Posts: 36
#1: Sep 15 '09
HI can anyone help me with a function of javascript ... that calculates the sum of all colums at the very last row and also sum of all rows at the very last coloum....

It wiuld be like a 2-d array sum.. But i am new to javascript so totally lost....
I want the total to be updated as soon as any value changes in any cell.....

Please please help me
gits's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,126
#2: Sep 15 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


please show what you have done so far ...

kind regards
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,066
#3: Sep 15 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Hi Tarunkhatri,

Is this question the same as your other question titled:
"I want to sum values in rows and coloums of a table."?
Member
 
Join Date: Sep 2009
Location: London
Posts: 36
#4: Sep 16 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Yes Frinavale,

Its the same, but there i tried to show my code which i develpoed thn I came to know tht it is not relevaly enough.
I wanted a simple function which is adding value of all prior rows and coloms (not by using property getelementby Tagname as its not supported by IE). And also wanted to know how can I call tht in my actual table other than defining the table ID.
RamananKalirajan's Avatar
Needs Regular Fix
 
Join Date: Mar 2008
Location: Chennai - India
Posts: 348
#5: Sep 16 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Hi I have tried one, But i dont know wether it fits into your requriement.

JS: Code
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.     function getColumnCount()
  3.     {
  4.         return document.getElementById('myTable').getElementsByTagName('tr')[0].getElementsByTagName('td').length;         
  5.     }
  6.  
  7.     function getRowCount()
  8.     {
  9.         return document.getElementById('myTable').rows.length;
  10.     }
  11.  
  12.     function doAdd(ths)
  13.     {
  14.         //alert(ths.parentNode.cellIndex);
  15.         //alert(getColumnCount());
  16.         var lastCol = getColumnCount()-1;
  17.         var lastRow = getRowCount()-1;
  18.         //for Column Sum
  19.          var table = document.getElementById("myTable");
  20.        var row = table.rows[ths.parentNode.parentNode.rowIndex];
  21.        var colSum=0;
  22.        for(var i=0;i<lastCol;i++)
  23.             colSum=eval(colSum) + eval(row.cells[i].childNodes[0].value);
  24.         row.cells[lastCol].innerHTML = colSum;
  25.  
  26.         //for Row Sum
  27.         var cIndex = ths.parentNode.cellIndex;
  28.         //alert(cIndex);
  29.         var rowSum = 0;
  30.         for(var i=0;i<lastRow;i++)
  31.             rowSum = eval(rowSum) + parseInt(table.rows[i].cells[cIndex].childNodes[0].value);
  32.         table.rows[lastRow].cells[cIndex].innerHTML = rowSum;
  33.  
  34.  
  35.         //for the final Value in the last row last column
  36.         var finSum = 0;
  37.         for(var i=0;i<lastRow;i++)
  38.             finSum = eval(finSum) + parseInt(table.rows[i].cells[lastCol].innerHTML);
  39.         for(var i=0;i<lastCol;i++)
  40.             finSum=eval(finSum) + eval(table.rows[lastRow].cells[i].innerHTML);
  41.         table.rows[lastRow].cells[lastCol].innerHTML = finSum;
  42.     }
  43. </script>
HTML Code:
Expand|Select|Wrap|Line Numbers
  1. <table cellspacing="0" cellpadding="0" width="100%" border="1" id="myTable">
  2.     <tr>
  3.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  4.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  5.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  6.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  7.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  8.         <td>0</td>
  9.     </tr>
  10.     <tr>
  11.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  12.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  13.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  14.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  15.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  16.         <td>0</td>
  17.     </tr>
  18.     <tr>
  19.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  20.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  21.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  22.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  23.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  24.         <td>0</td>
  25.     </tr>
  26.     <tr>
  27.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  28.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  29.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  30.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  31.         <td><input type="text" value="0" onchange="doAdd(this)"></td>
  32.         <td>0</td>
  33.     </tr>
  34.     <tr>
  35.         <td>0</td>
  36.         <td>0</td>
  37.         <td>0</td>
  38.         <td>0</td>
  39.         <td>0</td>
  40.         <td>0</td>
  41.     </tr>
  42. </table>

Thanks and Regards
Ramanan Kalirajan
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,629
#6: Sep 16 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Quote:

Originally Posted by RamananKalirajan View Post

Expand|Select|Wrap|Line Numbers
  1.         //for the final Value in the last row last column
  2.         var finSum = 0;
  3.         for(var i=0;i<lastRow;i++)
  4.             finSum = eval(finSum) + parseInt(table.rows[i].cells[lastCol].innerHTML);
  5.         for(var i=0;i<lastCol;i++)
  6.             finSum=eval(finSum) + eval(table.rows[lastRow].cells[i].innerHTML);
  7.         table.rows[lastRow].cells[lastCol].innerHTML = finSum;
  8.     }

isn’t that overly complicated? all you need is to loop over every <input> element…

Expand|Select|Wrap|Line Numbers
  1. // using some slightly modified HTML
  2. function sumTotal()
  3. {
  4.         // "all" = ID of the display cell
  5.     var total = new Summe("all");
  6.  
  7.         // Object.applyForEach() similar to Array.forEach()
  8.     document.getElementsByTagName("input").applyForEach(function() { total.add(this.value); });
  9.  
  10.     total.show();
  11. }
  12.  
  13. // going MVC
  14. function Summe(output_id)
  15. {
  16.     this.out = output_id;
  17.     this.sum = 0;
  18. }
  19.  
  20. Summe.prototype.add = function(x)
  21. {
  22.     var y = parseFloat(x);
  23.     if (!isNaN(y))
  24.         this.sum += y;
  25. }
  26.  
  27. Summe.prototype.show = function()
  28. {
  29.     var td = document.getElementById(this.out)
  30.     if (td)
  31.         td.innerHTML = this.sum;
  32. }
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,066
#7: Sep 16 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Quote:

Originally Posted by tarunkhatri View Post

Yes Frinavale,

Its the same, but there i tried to show my code which i develpoed thn I came to know tht it is not relevaly enough.
I wanted a simple function which is adding value of all prior rows and coloms (not by using property getelementby Tagname as its not supported by IE). And also wanted to know how can I call tht in my actual table other than defining the table ID.

What version of IE are you using?

I use the getElementsByTagName() method all the time. It works fine in IE7 and IE8. I haven't tested it in IE6...but then again IE6 is 2 versions ago and is old enough for me to justify not supporting any more.

This doesn't have to be complicated. All you have to do is grab all of the rows in the table. Retrieve the number of columns in the table and create an array that will hold all of the sums of the columns (where each element in the array corresponds to a column). Loop through the rows and for each row loop through it's cells (columns) adding their values to the value in the array....

the following is a rough outline of what I was talking about...I haven't tested it and can see some obvious ways to make it crash but here you go:
Expand|Select|Wrap|Line Numbers
  1. var theTable = document.getElementById("numbersTable");
  2.  var rows = theTable.getElementsByTagName("tr");
  3.  if(rows.length > 0)
  4.  {
  5.    var numColumns = rows[0].getElementsByTagName("td").length;
  6.    var columnSums = new Array(numColumns);
  7.    var cols = 0;
  8.    for(cols = 0; cols < columnSums.length; cols++)
  9.    {
  10.      columnSums[cols] = Number(0);
  11.    }
  12.    var rowIndex = 0;
  13.    for(rowIndex = 0; rowIndex < rows.length; rowIndex++)
  14.    {
  15.      var cells = rows[rowIndex].getElementsByTagName("td");
  16.      var cellIndex = 0;
  17.      for(cellIndex = 0; cellIndex < cells.length; cellIndex++)
  18.      {
  19.        var cellValue = Number(cells[cellIndex].innerHTML);
  20.        columnSums[cellIndex] = Number(columnSums[cellIndex]) + cellValue;
  21.      }
  22.    }
  23.    var i;
  24.    for(i=0; i<columnSums.length; i++)
  25.    {
  26.      alert("column: " + i +" sum: " +columnSums[i]);
  27.    }
  28.  }else{ 
  29.     alert("no rows");
  30.  }
Member
 
Join Date: Sep 2009
Location: London
Posts: 36
#8: Sep 16 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


HI Ramanan , Dormi & Frina,

The code provided by Ramanan did my job.. you all are such gr8 guys .. thanks very very much... Ramanan you made my lide easier.. God bless u all
Member
 
Join Date: Sep 2009
Location: London
Posts: 36
#9: Sep 16 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Ramanan,

Can u pls explain what is the significance of writing parentNode 2 times ths.parentNode.parentNode.rowIndex
RamananKalirajan's Avatar
Needs Regular Fix
 
Join Date: Mar 2008
Location: Chennai - India
Posts: 348
#10: Sep 17 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


In the Code ths.parentNode.parentNode.rowIndex, the "ths" is your input button object what you clicked. It has a parent Table Cell -> first parentNode and Table Cell has the parent Table Row so the second parentNode which will give you the table row object, from that you can fetch the row Index

Thanks and Regards
Ramanan Kalirajan
Member
 
Join Date: Sep 2009
Location: London
Posts: 36
#11: Sep 17 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Ohh yeah... I understand your complete code now.. It was really very very good. Thank you. .But as all my values are comin from a database table .

With onhange event I also wanted OnLoad event. I did it this way
"<input type="text" value="0" size = "2" onchange="doAdd(this)" onload="doAdd(this)">"

But Onload dosnt work here.

Thanks for al your help.

Kind Regards
Tarun
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,629
#12: Sep 17 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Quote:

Originally Posted by tarunkhatri View Post

But Onload dosnt work here.

It works, but not the way you expect it. onload basically says that the code is to be executed when the element finished loding. this does not mean that the full table is ready yet, so the script might miss some important details.

PS. to me this onload event seems futile
Member
 
Join Date: Sep 2009
Location: London
Posts: 36
#13: Sep 17 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


I understand your point but I am using this even in every <td> with my onchange event. Not at the table level. So every time a td loads with some value frm databse it should add it to the total . Dont knw wht the problem is.

I
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,629
#14: Sep 17 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


first, you’re not using the event on <td>, but <input>

second, why should you calculate the total while the table (and with it the form elements) is still built, ain’t it enough to do that, once the page has finished?

third, that would spare you (rows * columns – 1)* function calls.

* - if you, for example, have a 11 x 14 table and an approximate function run time of 100 ms, you’d save 15 s of time !!!
Member
 
Join Date: Sep 2009
Location: London
Posts: 36
#15: Sep 17 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Ohh.. U are absolutly right Dormi. what a stupid thing I was about to do.

I think I need some different event which works when the complete table is loaded.
RamananKalirajan's Avatar
Needs Regular Fix
 
Join Date: Mar 2008
Location: Chennai - India
Posts: 348
#16: Sep 18 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


To Dormilich,
Yes The way what you have specified for the final td row sum and column sum is an efficient one, when compared to mine. I will update myself Dormilich. Thanks for the suggestion.

Thanks and Regards
Ramanan Kalirajan
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,629
#17: Sep 18 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Quote:

Originally Posted by RamananKalirajan View Post

Thanks for the suggestion.

you can use a similar code for the row sum, you only need to use the <tr> as starting point.

unfortunately, there is nothing similar available for columns, except maybe using class names (where you’d have the same code for rows and columns).
Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,629
#18: Sep 18 '09

re: function for Calculating sum of values in row and coloms of html table by javascript


Quote:

Originally Posted by tarunkhatri View Post

I think I need some different event which works when the complete table is loaded.

Expand|Select|Wrap|Line Numbers
  1. addEvent(window, "load", func);
Reply