Often, in forms, fields depend on each other. For example, the sales tax may depend on
which state the customer lives in. Shipping charges may depend on the total weight of the
order. The total weight of the order may depend on the number of items ordered. And so
on.
An example
Let’s say you have a 3-line order form and you want to display a subtotal that is the sum
of the amounts on the 3 lines. How can you do this in JavaScript, in a PDF form? It’s
actually pretty easy. In the Field Properties dialog of the Subtotal field, add a JavaScript
action to the Calculate tab. Your custom calculation code will look something like:
var field1 = this.getField('FirstItem');
var field2 = this.getField('2ndItem');
var field3 = this.getField('3rdItem');
var subtotal = this.getField('Subtotal');
subtotal.value = field1.value + field2.value + field3.value;
This is a pretty common idiom in PDF JavaScript programming, so if it doesn’t seem
familiar to you, you should spend a few moments studying it.
We haven’t written this code in the most elegant manner, by any means. Note that when you
are setting up the Field Properties for your form, you can give your fields names like
Item.1, Item.2, Item.3, etc. That way, if you need to change an appearance attribute
globally, you can do something like:
var items = this.getField('Item');
items.fillColor = color.red;
Editing color pattern
With these two lines of code, you can change the fill color for an unlimited number of
fields, at once. The trick is to utilize JavaScript’s ability to construct name trees out of
objects with similar names.
Note: The name-overloading trick will not work for setting field values. There,
you have to obtain individual references to the values and set them one by one.
But the point is, if you need to bind field dependencies, it is quite easy to do so in
JavaScript, in a PDF form. The idea is to attach a script to a field action, then use that
script to access the values of the fields you are interested in. This is a common situation
in forms of all kinds.