Skip to main content
Known Participant
May 5, 2017
Answered

average ignoring empty fields & zero values

  • May 5, 2017
  • 1 reply
  • 6241 views

hi, in my form i want to calculate average in 40 text fields. fields names are AB-1, AB-2, AB-3, etc up to AB-40. i have found bellow code that really works but only issue is that code not ignoring zero values. so can u pls help me edit bellow code to ignore zero. thanks..

// Initialize variables

var num = 0;

var sum = 0;

// Loop through the input fields

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

  var f = getField("AB-" + i);

  if (f.valueAsString) {

  // increment the non-blank field counter

  num++;

  // add the field value to the running total

  sum += +f.value;

  }

}

// Calculate the average

if (num) {

  event.value = sum / num;

} else {

  // All fields are empty, so set to blank

  event.value = "";

}

PDF Form Field calculates AVERAGE incorrectly (PDF Forms)

This topic has been closed for replies.
Correct answer Bernd Alheit

Use this:

// Initialize variables

var i, v, num = 0, sum = 0;

// Loop through the input fields

for (i = 1; i <= 40; i++) {

  v = +getField("AB-" + i).value;

  if (v !== 0) {

  // increment the non-blank/zero field counter

  num++;

  // add the field value to the running total

  sum += v;

  }

}

// Calculate the average

if (num) {

  event.value = sum / num;

} else {

  // All fields are empty, so set to blank

  event.value = "";

}

1 reply

Inspiring
May 5, 2017

You could change it to something like the following:

// Initialize variables

var i, v, num = 0, sum = 0;

// Loop through the input fields

for (i = 1; i <= 40; i++) {

  v = +getField("AB-" + i).value;

  if (v !== 0) {

  // increment the non-blank/zero field counter

  num++;

  // add the field value to the running total

  sum += +f.value;

  }

}

// Calculate the average

if (num) {

  event.value = sum / num;

} else {

  // All fields are empty, so set to blank

  event.value = "";

}

omanbuxAuthor
Known Participant
May 5, 2017

hi, thanks a lot for your code but answer giving zero & not calculating correctly..

Bernd Alheit
Community Expert
Bernd AlheitCommunity ExpertCorrect answer
Community Expert
May 5, 2017

Use this:

// Initialize variables

var i, v, num = 0, sum = 0;

// Loop through the input fields

for (i = 1; i <= 40; i++) {

  v = +getField("AB-" + i).value;

  if (v !== 0) {

  // increment the non-blank/zero field counter

  num++;

  // add the field value to the running total

  sum += v;

  }

}

// Calculate the average

if (num) {

  event.value = sum / num;

} else {

  // All fields are empty, so set to blank

  event.value = "";

}