459,652 Members | 1,422 Online
Need help? Post your question and get tips & solutions from a community of 459,652 IT Pros & Developers. It's quick & easy.

# Javascript: Sum up columns of a table

 P: 55 Hi all, I have a simple table set up in which a user can insert values into the boxes and onkeydown it will sum up the column. Table: Expand|Select|Wrap|Line Numbers
javascript: Expand|Select|Wrap|Line Numbers function calcTotal(txtBox, totBox)           {             var col = txtBox.parentNode.parentNode.parentNode;             var inputs = col.getElementsByTagName("input"); //Get input boxes              sum = 0;    //Set sum to 0               for (i=0; i< inputs.length; i++)              {                 if (inputs[i].type == "text")                  {                     if(inputs[i].id.indexOf(totBox) == -1) //Pass id of total text box                     {                         if (inputs[i].value != null && inputs[i].value != "")                          sum += parseInt(inputs[i].value); //Calculate the total                     }                     else                     {                         inputs[i].value = sum;  //Store total in box                     }                  }              }          }   I think my problem is I am getting the wrong objects when traversing through the DOM of the table, think I may be getting the tbody rather than the column, so I need help in getting the columns to sum them up if anyone can help. Many thanks in advance. Mar 22 '09 #1
13 Replies

 100+ P: 607 Hi... I have just changed some part of your code.... This is one way of summing the column.. you can work in n no.. of ways to find the sum... HTML Code Expand|Select|Wrap|Line Numbers
JS Code Expand|Select|Wrap|Line Numbers function calcTotal(txtBox, totBox) {     var totVal;     try     {      totVal = document.getElementById(totBox).value;     if(totVal!= null && totVal!='')      {        document.getElementById(totBox).value= eval(parseInt(document.getElementById(totBox).value) + parseInt(txtBox.value));         }      else      {         document.getElementById(totBox).value= txtBox.value;                 }     }     catch(e)     {} } Regards Ramanan Kalirajan Mar 24 '09 #2

 P: 55 Thank you very much that does the job nicely :) Mar 25 '09 #3

 Expert Mod 15k+ P: 16,027 Ugh! No need for the eval on line 10 - the parseInt will add up nicely. Mar 28 '09 #4

 P: 4 This second solution works really well except (and my javascript understanding is almost nil) the NaN comes up if a field is tabbled through/nothing is entered in a box... How can that be addressed? Thank you. Dec 11 '09 #5

 Expert Mod 15k+ P: 16,027 Use the isNaN function. See also http://www.w3schools.com/jsref/jsref_isnan.asp Dec 12 '09 #6

 P: 4 Thanks, acoder. I figured out a solution for the original question and I managed to edit the preceding code to total both rows and columns. Here's the next question: can this be further altered so that changes to the fields can be counted - right now it just keeps adding to the totals but I want it to keep a running total of the current numbers only. Possible? Javascript Expand|Select|Wrap|Line Numbers   function calcTotal(txtBox, totBox, rowBox)  {  //val(txtBox.item); //val(txtBox  if (txtBox.value.length!=0){     var totColVal;      var totRowVal;     try      {       totColVal = document.getElementById(totBox).value;      if(totColVal!= null && totColVal!='')       {         document.getElementById(totBox).value= eval(parseInt(document.getElementById(totBox).value) + parseInt(txtBox.value));          }       else       {          document.getElementById(totBox).value= txtBox.value;                  }      }      catch(e)      {}       try      {       totRowVal = document.getElementById(rowBox).value;      if(totRowVal!= null && totRowVal!='')       {       document.getElementById(rowBox).value= (parseInt(document.getElementById(rowBox).value) + parseInt(txtBox.value));          }       else       {          document.getElementById(rowBox).value= txtBox.value;                  }      }      catch(e)      {}  } }     HTML Expand|Select|Wrap|Line Numbers
Dec 21 '09 #7

 Expert Mod 15k+ P: 16,027 You'll have to recalculate the totals each time. If you want to get a bit more complicated, you could store the values in a 2-dimensional array and change the corresponding value and then recalculate using the array (so that you don't have to access all of the elements each time). PS. eval is not required in your code. Dec 22 '09 #8

 P: 4 Thanks again, acoder. (FYI: I really don't know javascript so try not to laugh at this pitiful effort) Here's an attempt at using an array to calculate row/col values. BTW: The column headers are paycodes not just some seeminly random selection of numbers . Javascript Expand|Select|Wrap|Line Numbers function calcTotal(cell,row,col){ var total=0; var box={'1000':{},'1001':{},'1002':{},'1005':{},'1007':{},'1003':{},'1020':{},'1035':{},'1038':{},'1045':{},'1066':{},'1067':{},'Other':{}};     box[col][row]=cell;     for (j=0;j<2;j++){         if (box[col][j]>=0){             total+=(box[col][j]);             }         } document.getElementById(col).value; document.getElementById(row).value; } HTML Expand|Select|Wrap|Line Numbers
mon12/24
tue12/25
wed12/26
totals                             One big question: Are the numbers stored in the array for the session? or will the array be reset when the function is executed? and if the latter...how can the values be preserved for the session? Another question - Why won't box[i] work for box[box[i]][i] - is that recursive? I have to admit to being a little lost in the array... The last two lines are just a hail-mary that I pulled from the preceding code. So how crazy is this code, anyway? rotfl or lmao? Thank you! Dec 23 '09 #9

 P: 4 So I've pretty much figured this one out but am still trying to allow only numeric entries (including decimals)... ended up abandoning the 2xArray and decided to just loop through each value for a given row/column - so far, so good. One odd thing - the columns wouldn't total until I placed that loop first - any ideas on why that would be? Javascript Expand|Select|Wrap|Line Numbers function calculate(col, row){ var numericExpression = /^[0-9]+\$/; //verify numeric - needs to allow for decimals though...hmmm...     if(document.getElementById(col+"-"+row).value.match(numericExpression)){ var input=0;  //initalize variable to get entered value var rowTot=0; //initalize variable to capture row totals var colTot=0; //initalize variable to capture column totals //setup up array for paycodes/column headers  codes=new Array('1000','1001','1002','1005','1007','1003','1020','1035','1038','1045','1066','1067','Other');  //loop through all of the text fields for a given column and total them         for (i=0;i<2;i++){         input=(document.getElementById(col+'-'+i).value)*1         colTot=colTot+input;         document.getElementById(col).value = colTot;         } //loop through all of the text fields for a given row and total them         for (j=0;j<13;j++){         input=(document.getElementById(((codes[j])+'-'+row)).value)*1         rowTot=rowTot+input;         document.getElementById('row'+row).value = rowTot;         }     }     //if the entry isn't numeric then return no value     else {document.getElementById(col+"-"+row).value="";} } html Expand|Select|Wrap|Line Numbers Enter numbers here:

Dec 23 '09 #10

 Expert Mod 5K+ P: 8,639 2 notes from my side: id values must only start with a letter or underscore, anything else is browser courtsy. this and this thread also deal with summing up a table, maybe they give you some more insight. Dec 24 '09 #11

 Expert Mod 15k+ P: 16,027 So I've pretty much figured this one out but am still trying to allow only numeric entries (including decimals)... Either use a floating point regular expression, e.g. something like: /^[0-9]+\.[0-9]{2}\$/ or parseFloat with isNaN One odd thing - the columns wouldn't total until I placed that loop first - any ideas on why that would be? What would happen? Dec 30 '09 #12

 P: 4 I have a form. Diffrent fields that add up to a sub total. I need to sub totals to autocomplete the TOTAL sum??? I have tried a few things.. but it did not work. Im quite new to this.. I have used some code examples from the site.. (thanks)... I just need to TOTAL SUM to display when i add some numericals to the top fields?? where am I going wrong??? Expand|Select|Wrap|Line Numbers     function calculate(col, row){ var numericExpression = /^[0-9]+\$/; //verify numeric - needs to allow for decimals though...hmmm...     if(document.getElementById(col+"-"+row).value.match(numericExpression)){ var input=0;  //initalize variable to get entered value var rowTot=0; //initalize variable to capture row totals var colTot=0; //initalize variable to capture column totals //setup up array for paycodes/column headers  codes=new Array('1000','1001','1002','1005','1007','1003','1020','1035','1038','1045','1066','1067','Other');  //loop through all of the text fields for a given column and total them         for (i=0;i<2;i++){         input=(document.getElementById(col+'-'+i).value)*1         colTot=colTot+input;         document.getElementById(col).value = colTot;         } //loop through all of the text fields for a given row and total them         for (j=0;j<13;j++){         input=(document.getElementById(((codes[j])+'-'+row)).value)*1         rowTot=rowTot+input;         document.getElementById('row'+row).value = rowTot;         }     }     //if the entry isn't numeric then return no value     else {document.getElementById(col+"-"+row).value="";} }   function updatesum() { document.form.sum.value = (document.form.sum1.value -0) + (document.form.sum2.value -0); }

Enter numbers here:

sub total                         sub total                         Total Sum:          May 20 '10 #13

 100+ P: 607 In the Line Number 24, You are accessing an element with the id ('row'+row). But in the HTML, there is no element with id like that. Check for that. That is the problem. Thanks and Regards Ramanan Kalirajan Sep 15 '10 #14