You are viewing limited content. For full access, please sign in.

Question

Question

JS to find the average of multiple fields from multiple sections.

asked on February 22, 2016

Hello everyone,

 

Here is the scenario. I am currently using JS to find the average of a set of scores that are being entered into a table on a section. The value is then entered into field outside the table but still in the section. There is a potential total of 9 different scores.

 

The trouble I am having is: 

1) I pieced a majority of this together from JS here on answers and from a fellow engineer, so I am not too familiar with JS.

 

2) While I was able to find code and manipulate it to get the average from one table in one section, how would I be able to dynamically calculate the average of these newly calculated scores across the currently entered values? Also, how do I make sure to not count against any empty values (ex. If we only used 7/9 scores how can I make sure it is the average of 7 and not the entire 9?)

 

This is in Forms 9.2 and I have attached the current JS below. I tried my best to comment out each section of code so that it is easy to identify.

 

To sum it all up: Can anyone point me in the direction of JS that will take multiple fields from different sections and average them, but only if that field has a value. There is a potential of having up to 9 different fields.

Thanks in advance!

Current JS.txt (20.25 KB)
0 0

Answer

SELECTED ANSWER
replied on February 22, 2016 Show version history

Hi Alex,

Try giving each of the score fields a class (i.e. "subtotal"). Then you can add each score only if its value is not blank. Each time a score is added, add 1 to the number of scores, and then divide by that number (giving you the average). For example:

$('.subtotal input').on('change', function(){
  var sum = 0, n = 0;
  $('.subtotal input').each(function(){
    if ($(this).val() != ''){
      sum += parseFloat($(this).val());
      n += 1;
    }
  });
  $('.total input').val(sum/n);
});

The "total" input is the average of the scores. You can adjust the number of decimals for this field by using the .toFixed() method

With Forms 10, field calculations/formulas come out-of-the-box, based on the OpenFormula standard. 

Let me know if this works for you!

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.