Using Formula Scripting to Calculate an Average

A hidden formula item can be added to an eForm to calculate the average of certain values collected from the eForm questions.

Generating a simple average is straightforward if you can always assume a fixed number of answered questions (i.e. if you require a response to all questions).

For example, for five questions with refs 'q1', 'q2', 'q3', 'q4', and 'q5;, your formula would look like this:

(q1.p + q2.p + q3.p + q4.p + q5.p) / 5

However, it gets a bit trickier if you only want to count a question when it’s answered. Using the above example, if q3 was left blank, you would only want to divide by 4 when generating the average. That means you need to calculate the denominator by adding 1 for each answered question.

This is what your new formula would look like:

(q1.p + q2.p + q3.p + q4.p + q5.p) / ((q1.r != '' ? 1 : 0) + (q2.r != '' ? 1 : 0) + (q3.r != '' ? 1 : 0) + (q4.r != '' ? 1 : 0) + (q5.r != '' ? 1 : 0))

The '.r' is the literal response, so:

  • q1.r == '' means the answer is blank
  • q1.r == 'N' means the answer is 'No'
  • q1.r == 'Y' means the answer is 'Yes'. 

The statements (q1.r != '' ? 1 : 0) are JavaScript shorthand for saying "use 1 if q1.r isn’t empty; otherwise use 0".

Was this article helpful?
0 out of 1 found this helpful
Have more questions? Submit a request