Javascript to sum cells in a column

Brian3_14

02-04-2015

Hi all -

I've got an expanding table (rows can be added) and I'm trying to use the footer row of the column to compute the average of cells that don't have a value of 0.

Form Calc is usually great, but in this instance, I need to divide the sum by the number of cells that are not zero and I'm not sure how to do that via Form Calc.

Successfully used javascript to both identify the total number of instances and identify the number of instances that are zero, so the denominator part of the equation is fine. (# of instances - # of zeros = denominator.)

Now it's just the numerator. It's got to be a loop, right?

Table is called: table1

Row is called: data

cell is called: eValue

Any thoughts? Or more efficient methods? Thanks so much.

B

Accepted Solutions (1)

Accepted Solutions (1)

radzmar

MVP

03-04-2015

Hi,

a solution in FormCalc could look this way:


form1.#subform[0].table1.footer.sum::calculate - (FormCalc, client)


var c = 0


var s = 0


for i = 0 upto (_data.count - 1) do


  if (data[i].eValue gt 0) then


  c = Sum(c, 1)


  s = Sum(s, data[i].eValue)


  endif


endfor



if (s gt 0 and c gt 0) then


  $ = Round(s / c)


else


  $ = 0


endif


Put this scriot into the calculate event of the cell of the footer row.

Answers (5)

Answers (5)

Brian3_14

03-04-2015

Radz,

Worked like a charm.  Thanks much - and I won't tell you the embarrassingly long way I was going.

Any recommended reading for LD and coding?

Thanks again,

Brian

jasotastic81

03-04-2015

Something like this?


var num = 0, den = 0, rowList = xfa.resolveNodes("Table1.Row1[*]");


 


for (var i = 0; i< rowList.length; i++){


  if (!rowList.item(i).nfNumber.isNull && parseFloat(rowList.item(i).nfNumber.rawValue) != 0) {


  num += parseFloat(rowList.item(i).nfNumber.rawValue);


  den++;


}


}


if (den !=0) this.rawValue = parseFloat(num)/parseInt(den);


else this.rawValue = 0;