473,320 Members | 1,982 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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

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
Sep 15 '09 #1
18 37279
gits
5,390 Expert Mod 4TB
please show what you have done so far ...

kind regards
Sep 15 '09 #2
Frinavale
9,735 Expert Mod 8TB
Hi Tarunkhatri,

Is this question the same as your other question titled:
"http://bytes.com/topic/javascript/an...-coloums-table"?
Sep 15 '09 #3
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.
Sep 16 '09 #4
RamananKalirajan
608 512MB
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
Sep 16 '09 #5
Dormilich
8,658 Expert Mod 8TB
@RamananKalirajan
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. }
Sep 16 '09 #6
Frinavale
9,735 Expert Mod 8TB
@tarunkhatri
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.  }
Sep 16 '09 #7
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
Sep 16 '09 #8
Ramanan,

Can u pls explain what is the significance of writing parentNode 2 times ths.parentNode.parentNode.rowIndex
Sep 16 '09 #9
RamananKalirajan
608 512MB
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
Sep 17 '09 #10
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
Sep 17 '09 #11
Dormilich
8,658 Expert Mod 8TB
@tarunkhatri
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
Sep 17 '09 #12
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
Sep 17 '09 #13
Dormilich
8,658 Expert Mod 8TB
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 !!!
Sep 17 '09 #14
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.
Sep 17 '09 #15
RamananKalirajan
608 512MB
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
Sep 18 '09 #16
Dormilich
8,658 Expert Mod 8TB
@RamananKalirajan
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).
Sep 18 '09 #17
Dormilich
8,658 Expert Mod 8TB
@tarunkhatri
Expand|Select|Wrap|Line Numbers
  1. addEvent(window, "load", func);
Sep 18 '09 #18
I have edited the above script inorder to work with body onload and changing values in columns

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  5. <title>Time Sheet</title>
  6. </head>
  7. <script type="text/javascript"> 
  8. function getColumnCount() 
  9. return document.getElementById('myTable').getElementsByTagName('tr')[0].getElementsByTagName('td').length; 
  10.  
  11. function getRowCount() 
  12. return document.getElementById('myTable').rows.length; 
  13.  
  14. function doAdd(ths) {
  15.  
  16.         //alert("ths==>"+ths);
  17.         var lastCol = getColumnCount()-1; 
  18.         var lastRow = getRowCount()-1; 
  19.  
  20.         //alert("lastCol==>"+lastCol +" lastRow==>"+lastRow);
  21.  
  22.         //for Column Sum 
  23.  
  24.         var table = document.getElementById("myTable"); 
  25.         //alert(ths.parentNode.parentNode.rowIndex);
  26.         var row;
  27.         var colSum;
  28.         var colValue;
  29.         if(ths == 'on'){
  30.             //alert(1111111);
  31.             for(var t=0;t<lastRow;t++){
  32.                 row = table.rows[t];
  33.                 //alert("row==>"+row)
  34.             colSum=0;
  35.             for(var i=0;i<lastCol;i++){
  36.                  colValue = row.cells[i].childNodes[0].value;
  37.                 if(colValue != '' && !isNaN(colValue)){
  38.                     colSum=eval(colSum) + eval(colValue);
  39.                 } 
  40.             }
  41.                 row.cells[lastCol].innerHTML = colSum;
  42.             //    alert("==>"+row.cells[lastCol].innerHTML);
  43.             }
  44.         }else{
  45.             row = table.rows[ths.parentNode.parentNode.rowIndex];
  46.             colSum=0;
  47.             for(var i=0;i<lastCol;i++){
  48.                  colValue = row.cells[i].childNodes[0].value;
  49.                     if(colValue != '' && !isNaN(colValue)){
  50.                     colSum=eval(colSum) + eval(colValue);
  51.                 } 
  52.             }
  53.                 row.cells[lastCol].innerHTML = colSum;
  54.         } 
  55.  
  56.         //for Row Sum 
  57.  
  58.         //alert("cellIndex==>"+cIndex);
  59.  
  60.         var rowSum;
  61.         var columnValue;
  62.         if(ths == 'on'){
  63.  
  64.             for(var b=0;b<lastRow+1;b++){
  65.                 rowSum = 0;
  66.                 for(var i=0;i<lastCol-1;i++){ 
  67.                     //alert("i====>"+i+" value==>"+table.rows[i].cells[b].childNodes[0].value);
  68.                     columnValue =  table.rows[i].cells[b].childNodes[0].value;
  69.                     if(columnValue != '' && !isNaN(columnValue)){
  70.                         rowSum = eval(rowSum) + parseInt(columnValue);
  71.                     }
  72.                     //alert("rowSum==>"+rowSum);
  73.                     table.rows[lastRow].cells[b].innerHTML = rowSum; 
  74.                 }
  75.  
  76.             }
  77.  
  78.         }else{
  79.             var cIndex = ths.parentNode.cellIndex; 
  80.             //alert(cIndex); 
  81.             rowSum = 0; 
  82.             for(var i=0;i<lastRow;i++) {
  83.                 columnValue =  table.rows[i].cells[cIndex].childNodes[0].value;
  84.                 if(columnValue != '' && !isNaN(columnValue)){
  85.                     rowSum = eval(rowSum) + parseInt(columnValue);
  86.                 }
  87.             } 
  88.             table.rows[lastRow].cells[cIndex].innerHTML = rowSum; 
  89.         }
  90.  
  91.         //for the final Value in the last row last column 
  92.         var finSum = 0; 
  93.         for(var i=0;i<lastRow;i++) 
  94.         finSum = eval(finSum) + parseInt(table.rows[i].cells[lastCol].innerHTML); 
  95.         for(var i=0;i<lastCol;i++) 
  96.         finSum=eval(finSum) + eval(table.rows[lastRow].cells[i].innerHTML); 
  97.         table.rows[lastRow].cells[lastCol].innerHTML = finSum; 
  98.     } 
  99.  
  100. function timedRefresh(timeoutPeriod) {
  101.     setTimeout("location.reload(true);",timeoutPeriod);
  102. }
  103. </script>
  104. <body onload="doAdd('on')">
  105.  
  106. <table cellspacing="0" cellpadding="0" width="100%" border="1" id="myTable" > 
  107.     <tr> 
  108.         <td><input type="text" value="1" onchange="doAdd(this)"></td> 
  109.         <td><input type="text" value="1" onchange="doAdd(this)"></td> 
  110.         <td><input type="text" value="1" onchange="doAdd(this)"></td> 
  111.         <td><input type="text" value="1" onchange="doAdd(this)"></td> 
  112.         <td><input type="text" value="1" onchange="doAdd(this)"></td> 
  113.         <td>0</td> 
  114.     </tr> 
  115.     <tr> 
  116.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  117.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  118.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  119.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  120.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  121.         <td>0</td> 
  122.     </tr> 
  123.     <tr> 
  124.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  125.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  126.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  127.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  128.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  129.         <td>0</td> 
  130.     </tr> 
  131.     <tr> 
  132.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  133.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  134.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  135.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  136.         <td><input type="text" value="0" onchange="doAdd(this)"></td> 
  137.         <td>0</td> 
  138.     </tr> 
  139.     <tr> 
  140.         <td>0</td> 
  141.         <td>0</td> 
  142.         <td>0</td> 
  143.         <td>0</td> 
  144.         <td>0</td> 
  145.         <td>0</td> 
  146.     </tr> 
  147. </table> 
  148.  
  149.  
  150. </form>    
  151. </body>
  152. </html>
Please let me know incase of any issues..
Aug 9 '10 #19

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Marco | last post by:
Hello there ;) I'm trying to build a scrip that would open a page that has a table and then get all the values as variables so I can put them in a MySQL DB. The problem is that I don't really...
4
by: xzzy | last post by:
I have hit a wall with not being able to enumerate the items collection in a table row. given: <table runat=server id=table1> <tr> <td id=AAA>HowToReferenceThisValue</td> etc...
2
by: jonniethecodeprince | last post by:
Hi all, I was wondering if anyone could help me display the HTML in a javascript that displays a table of data of prototype cinema listings. This code brings up a Syntax error: Object...
0
by: veegamca | last post by:
Hi to All, Any one help me out, to assign values to HTML Table , which can be exported to Excel Sheet Thanks and Regards Veera
1
by: since | last post by:
I figured I would post my solution to the following. Resizable column tables. Search and replace values in a table. (IE only) Scrollable tables. Sortable tables. It is based on a lot...
0
by: Jeff | last post by:
hey asp.net 3.5 I'm developing a webportal which need to access a webpage of a external system. The external webpage contain a table which I want to retrieve the values from.. it is a html...
8
by: James Kimble | last post by:
Yeah I'm sure this is a stupid question. I've got a javascript source file with functions (creates a bar graph) I want to call from inside an html table cell so that the graph appears in the...
11
by: sanju | last post by:
Dear All, I have html table and this table contains 10 Rows and 2 column, I want every time this HTML page is called by the user to view the rows Randomly. How can I do this from JavaScript? ...
16
by: BaseballGraphs | last post by:
Hello, I am trying to filter an HTML table by div value using javascript. Here is my table in HTML: <table> <tr> <td><div align="center">1</div></td> <td><div align="left"...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.