PDF Form Field calculates AVERAGE incorrectly

I have a PDF Form field that is set to calculate the AVERAGE of 4 other fields. Each of those other fields has its validation set to allow only the values 1 through 3.

The Average field is dividing the total by 4 even if a person only fills out 2 of the fields. I thought AVERAGE would only count the fields that have a value in them. But it's seeing the ones that are blank as containing a 0, even though that is an invalid value for that field.

How can I fix this? The customer really wants the option of having up to 4 fields and wants an average of just the ones that are filled in. I thought that was what Average was supposed to do.

Is there a way to tell Acrobat to ignore the fields if their value is less than 1?


Matt Mayerchak


3 Answers

Voted Best Answer

You will have to use a custom JavaScript, which will allow you to detect which fields are empty and ignore them if they are. For example:

// Initialize variables
var num = 0;
var sum = 0;

// Loop through the input fields
for (var i = 1; i < 5; i++) {
var f = getField("text." + 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 = "";
}


This code assumes the fields are named "text.1", "text.2", ..."text.4", so change to match your field names


By George Johnson   

Thanks - I'll try that and report back how it goes.


Matt Mayerchak   

George,

It worked - thanks! - I really have to learn how to write javascripts.

One more request, if it's not too much to ask: Would you mind telling me how to write a custom validation script to just allow the #s 1 and 3? (not for the average field . . . for the fields that are being averaged)

I can set the range from 1 to 3 but apparently need to write a script to limit the field to either 1 or 3.


Matt Mayerchak   


Please specify a reason: