Trying to figure sum calculation for variable values

Cheri M
Kilo Sage

I am trying to build a catalog item that is based on a spreadsheet that used the =sum calculation.   I've found a few ideas out there but nothing that will work for me.   We'd like it to be just for this catalog item so not a business rule.   Currently I have 5 columns, 1st   year — 5th year and we'd like each column to show the total at the end (a total cost of ownership).   Please see screenshot.   I got the fields figured out, now I just need a formula.   We'd like the user to be able to see the change as they did with the spreadsheet and not have the sum just sent in the form. I will make the TCO (bottom) row read-only if I get this all figured out.

 

Thank you!

 

calculations.jpg

14 REPLIES 14

Drew, I'm using the script you posted:



  function total(rowNumber){    


          var total = 0;    


          for(int y = 1; y <= 5; y++){    


                    total += new Number(g_form.getValue("row_" + rowNumber + "_year_" + y))    


          }    


          g_form.setValue("row_" + rowNumber + "_total", total);    


  }


Not sure why I typed it but last I checked java script did not support the type of int.   The below assumes you would like to total a column at the bottom.   Please keep in mind you are going to have to do some error checking to make sure the data in the fields are numbers.



  function totalColumn(columnNumber){    


          var total = 0;    


          for(var y = 1; y <= 5; y++){    


                    total += new Number(g_form.getValue("row_" + y + "_year_" + columnNumber))    


          }    


          g_form.setValue("row_" + columnNumber + "_total", total);    


  }


emir_e_eminovic
Giga Contributor

remember to check for isNaN() on your variables, otherwise you can end up with all kinds of issues.


Good point, although I think I would also prevent the user from entering anything but 0-9 and decimal point.


salvadormarchan
Kilo Guru

A couple of pointers to look at:


• I normally use the Number function as suppose to the Number class


• Sometimes, wrapping them all in one line of code does not work [e.g. 4th line: total += new Number(g_form.getValue("row_" + y + "_year_" + columnNumber)) ]. I recommend breaking them as follows:



var myValue;


...


myValue = g_form.getValue("row_" + y + "_year_" + columnNumber);


total += Number(myValue);



I hope this helps.