© Jennifer Harder 2017

Jennifer Harder, Enhancing Adobe Acrobat DC Forms with JavaScript, https://doi.org/10.1007/978-1-4842-2893-7_6

6. Basic and Complex Calculations

Jennifer Harder

(1)Delta, British Columbia, Canada

In the first example of JavaScript calculations in this chapter, we will compare three methods: Value, simplified field notation (SFN), and JavaScript as found in the Calculate tab in the Text and Dropdown Menu form fields, as shown in Figure 6-1.

A449379_1_En_6_Fig1_HTML.gif
Figure 6-1. Inside the Acrobat Calculate Tab Examples PDF file

While Value is generally the most straightforward way of dealing with calculations for beginner form creators, you will soon discover that there are limitations to Value, so simplified field notation and JavaScript might be better options. This chapter will show the strengths and weaknesses of each method.

Note

If you want to work along in this lesson or review the final result, download the Chapter 6 files from www.apress.com/9781484228920 . The file with the label “Start” is the file without the code and the file with the label “End” is the final result. You will also find folders with original MS Word, Excel, and PDF files if you would like to edit them and a folder containing the original scripts if you would like to add them to your own PDF forms.

If you are creating your form from an original PDF, refer to the “Forms Review” section in Chapter 1.

Remember that to view the properties of a field you must select the Prepare Form tool; only then can you right-click or double-click a field to review its properties.

Getting Started

Let’s take the addition or sum example, which is common to all methods regardless of which method or option you choose in the Calculate tab. Refer to the Acrobat Calculate Tab PDF file in the folder for this chapter. Refer to Figure 6-2.

A449379_1_En_6_Fig2_HTML.jpg
Figure 6-2. The Calculate tab is common to all three methods we will discuss shortly

Sum Value

In the Calculate tab, select the “Value is the…” button and pick sum (+) from the dropdown menu. Notice there are field names of some of the fields in the form in the grey area (Figure 6-3).

A449379_1_En_6_Fig3_HTML.jpg
Figure 6-3. Entering the sum value into the Calculate tab

In this example and Figure 6-3, you are getting data or value from two fields: Object 1Sum and Object 2Sum. They add together in the field TotalSum to offer a result. These values were entered by selection using the Pick button.

Simplified Field Notation

Now let’s look at simplified field notation. Notice in the Calculate tab in Figure 6-4 that the button called Simplified Field Notation is selected.

A449379_1_En_6_Fig4_HTML.jpg
Figure 6-4. Entering the simplified field notation into the Calculate tab
Note

With SFN and JavaScript you cannot pick or select your fields; you must type the information directly into the JavaScript Editor. Refer to Figures 6-4 and 6-6.

The second way of accomplishing this is SFN, which is common to a program like Microsoft Excel. While this is similar to the value sum example, there are differences. In the previous sum example, you could have spaces between the words in the fields. However, Object 1Sum in SFN must be written as Object1Sum. There can be no breaks using SFN. This rule is very strict. Any break in the name of the field and it will not calculate. If you need a break, use an underscore (_), as in Object1Sum_2 or use what is known as the camel method where each new word is capitalized, but with no breaks (ObjectSum).

Another difference to SFN is the addition of a plus symbol (+) to show that you are adding these two field values within the field TotalSum_2. If you were multiplying, you would use an asterisk (*), subtraction a minus (-), and division a slash (/). If you’ve ever taken algebra, you’ll be familiar with parentheses (). Whatever occurs within them happens first before the calculation continues. Refer to Figure 6-5.

A449379_1_En_6_Fig5_HTML.jpg
Figure 6-5. Entering the SFN into the Calculate tab for a more complex calculation

To type this code into the editor, you must first click the Edit button. Then you can type. When done, click OK to exit.

Here you can see (Object1MoreComplex*2) + (Object2MoreComplex-7) = TotalMoreComplex

If you put numbers into these fields, this should be your answer :

(5*2) + (10-7) = 13

JavaScript Custom Calculation Script

The final method we will look at is a custom calculation script . Figure 6-6 shows the “Custom calculation script” button selected.

A449379_1_En_6_Fig6_HTML.jpg
Figure 6-6. Entering the custom calculation script into the Calculate tab

To type this code into the editor, you must first click the Edit button. Then you can type. When done, click OK to exit.

In the case of JavaScript, you can again see that there are similarities and differences in the way the code is set up. In order to translate the fields into the language of JavaScript, you need to use variables to hold the fields. Variables act as information containers. In JavaScript, the word variable uses the short form var. After the word var you add a name. In this example, to keep it simple, let’s use the name a. This variable called a will now hold whatever value comes into the text field Object1Sum_3. Once a variable is named the first time, it does not need to have the word var attached and can be used anywhere in the script as just a. To ensure that the number input will follow through correctly, add this.getField which means “get the data in this field.” At the end of the variable, use a semicolon (;) to indicate that that is the end of this variable statement. The same is true for the second variable, b.

The final part of the script is

event.value = a.value + b.value;

It’s very similar to the SFN example. However, you need to add the .value on the end of each variable to remind Acrobat that you want the value of each and the final value to be added in the final field. The final field, TotalSum_3, is represented by event.value. In this final field, the event of the addition taking place is the result. It is important to note that the final field does not need a variable name because of the way Acrobat contains the script within the final field.

Where the naming of variables is concerned, it’s OK to have the names longer than one letter, like a. You can give them more meaningful names like age or sum. In the final example it would be written like this:

event.value = age.value + sum.value                          ;

A few other things to remember about variables are

  • All JavaScript variables must be identified with unique names.

  • Names can contain letters, digits, and underscores.

  • Names must begin with a letter.

  • Names are case sensitive (y and Y are different variables).

  • Reserved words (like JavaScript keywords) cannot be used as names. I would not create a variable like var event because event is a key JavaScript word used in the final event. For example, event.value = age.value + event.value; might not function since event.value has already been used once.

Final Thoughts

You have seen three ways in which addition can be done: Value, simplified field notation, and a JavaScript custom calculation script. However, which one is right for your project? Do you need to learn Acrobat JavaScript at all?

In most simple calculation projects, I recommend using Value or SFN in various parts of the form. However, if you take a look at the example, you will see Value and SFN do not equally cover all issues. For Value, you cannot subtract or divide. SFN cannot find minimum or maximum numbers. In this case, you may have to use a combination of both these calculations in your form.

Note

JavaScript can do all of these calculation as well as many others. Also, as you will see in Chapter 12, when the JavaScript becomes more complex, it’s not always a good idea to mix Values and SFN with JavaScript as this can lead to some fields not responding correctly. Consistent coding methods are crucial for form calculations to run smoothly.

For example,

var q = this.getField("Object1Minimum_3");
var r = this.getField("Object2Minimum_3");
event.value=Math.min(q.value,r.value);

You can use the JavaScript math formula Math.min to get my minimum number similar to the value example. You could use Math.max to get the maximum number. There are other math formulas that are not available to us via Value or SFN, but are with JavaScript:

  • Math.abs(x): Returns the absolute value of x.

  • Math.acos(x): Returns the arccosine of x, in radians.

  • Math.asin(x): Returns the arcsine of x, in radians.

  • Math.atan(x): Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians.

  • Math.atan2(y,x): Returns the arctangent of the quotient of its arguments.

  • Math.ceil(x): Returns x, rounded upwards to the nearest integer.

  • Math.cos(x): Returns the cosine of x (x is in radians).

  • Math.exp(x): Returns the value of Ex, where E is Euler’s number.

  • Math.floor(x): Returns x, rounded downwards to the nearest integer.

  • Math.log(x): Returns the natural logarithm (base E) of x.

  • Math.PI: Gives the formula of p.

  • Math.pow(x,y): Returns the value of x to the power of y.

  • Math.random(): Returns a random number between 0 and 1.

  • Math.round(x): Rounds x to the nearest integer. Example: Round up a subtotal.

  • Math.sin(x): Returns the sine of x (x is in radians).

  • Math.sqrt(x): Returns the square root of x.

  • Math.tan(x): Returns the tangent of an angle.

From www.w3schools.com/jsref/jsref_obj_math.asp .

One final thing, which you could not do in this form without JavaScript is format the number 0. Sometimes on a form you do not want the 0 to be present if no calculation has been added to the first two fields; you just want it blank. Refer to Figure 6-7.

A449379_1_En_6_Fig7_HTML.jpg
Figure 6-7. Adding a validation script into the Validate tab of the Total field. Before and after adding the script.

This looks better.

Along with the Calculate tab script, enter the following into your Validate tab:

// Custom Validate script for text field
if (event.value == 0) event.value = "";

To start off this script in text field Object1Sum_3, write a comment to remind yourself what you’re doing.

A double slash (//) always starts off a comment. They can be written anywhere in JavaScript and will not affect the calculations. Consider them a place for helpful reminders.

Another type of commenting you can use is for longer, paragraph-sized comments:

/* This type of comment is for lots of text */

However, I generally prefer to use // due to the small space Acrobat provides .

The Final Line of Code

if (event.value == 0) event.value = "";

This is what is known as a conditional statement and you will look at them in detail later. Essentially it is saying, “if no value or number from the other two fields has been entered (both are blank), then leave the final value field blank as well.”

One final item: If you used this script in subtraction or addition with negative numbers and you needed to see the 0, (Example: 5-5=0) you might not see the 0. If you need to see the 0 only when the fields are full, you can use a more complex and stricter validation.

== is not a strict comparison. A result like 5-5=0 might work, but 0-0=0 or 0x5=0 might not work because the validation regards 0 and a blank field as the same thing.

=== is a strict comparison, so now a result like 0-0=0 or 0x5=0 will work because the validation regards 0 and a blank field as not the same thing and will put a 0 in the results field. You could write the following to keep your 0:

if (event.value === 0) event.value = "";

However, Acrobat seems to act quirky and not get the intended result where the final field is blank if no values are added. So here’s the alternate code:

//Sum Validation to insure 0 is not missing from an actual calculation
if (a.value !== a.defaultValue && b.value !== b.defaultValue) {
event.value = a.value*1 + b.value*1 ;
} else {
event.value ="" ;
}

This code allows you to have the field blank if no numbers are in the other fields and still retain the 0 if the final result is 0. In this case, you used !== (strict not equal) which is similar to strict comparison, ===, but in reverse and checks the current value against the default. If no value is found in both of the other value fields, the event.value will remain blank. Notice you used another conditional statement, if/else.

For other operators and comparisons refer to www.w3schools.com/js/js_comparisons.asp .

Note

In the subtraction example, in the Calculate Tab Examples End Option 2 Validate PDF, change

event.value = a.value*1 + b.value*1 ;

to

event.value = f.value*1 - g.value*1;

For the code to operate correctly the values in the Validate tab must match what is in the Calculate tab.

When you are done viewing the forms, click the X in the upper right-hand corner of the Preview to close off the Prepare Form tool. Refer to the “Forms Review” section in Chapter 1 if you are unsure what this button looks like.

Dropdown Alternatives

As in Chapter 2, for this example, you can replace some of the text fields with dropdown menus to calculate. While similar to text fields, I find this method a good alternative if you want your client to use very specific values, and it eliminates the need for validation on each dropdown because the values are already set. You should not replace the final text field with a dropdown. Even though these Validate and Calculate tabs do work with dropdowns, the end result is really only one value. In Part 3, you will see how to use JavaScript to get more than one result into a dropdown menu when required.

Note

With dropdowns I left the Validation blank because I was using specific numbers. Unlike text fields, there always is a value and never a blank value. Refer to the Calculation Tab Example that contains a Dropdown Menus PDF in the file folder for this chapter.

Summary

In this chapter, you looked at the three ways you can add calculations to your form fields using the Calculate tab.

  • Value

  • Simplified field notation

  • JavaScript

While each example became progressively more complex, a broader range of possibilities opened up as you moved toward JavaScript.

You also saw how adding JavaScript to your Validation tab made it possible to see when the Total field was being utilized and when it was not. Giving clients accurate form information updates is important.

In the next chapter, you will explore how custom JavaScript can affect the Format tab when it comes to

  • Number

  • Percentage

  • Date

  • Time

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset