Actual script for Sum of Fields

Community Beginner ,
Apr 12, 2021 Apr 12, 2021

Copy link to clipboard

Copied

I feel like this should be easy to find, but for some reason it isn't.

 

If I have fields named Strata.1, Strata.2, Strata.3, Strata.4 etc... and I want to return the sum of all the Strata fields in a field named Strata_Total.

I know I can use the pull down menu and just choose Sum and select the checkbox for Strata.

 

But what is the actual script that is happening behind the curtain?

 

TOPICS
How to, JavaScript, PDF forms

Views

81

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Adobe Community Professional ,
Apr 12, 2021 Apr 12, 2021

Copy link to clipboard

Copied

You can read about basic field scripting here:

https://www.pdfscripting.com/public/PDF-Form-Scripting.cfm

 

And specically about calculations here:

https://acrobatusers.com/tutorials/how-to-do-not-so-simple-form-calculations/

 

But since you've done such a great job of naming your fields, here's an advanced calculation script:

 

var sum = 0;
this.getField("Strata").getArray().forEach(a=> sum+=Number(a.value));
event.value = sum;
Thom Parker - Software Developer at PDFScripting
Use the Acrobat JavaScript Reference early and often

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Most Valuable Participant ,
Apr 13, 2021 Apr 13, 2021

Copy link to clipboard

Copied

LATEST

I would advise against using this type of notation. It's not compatible with earlier versions of Acrobat and Reader and will not work there. Instead, you should stick to plain "vanilla" JS syntax, like this:

 

var sum = 0;
var fields = this.getField("Strata").getArray();
for (var i in fields) sum+=Number(fields[i].value);
event.value = sum;

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines