This tutorial shows you how to work with the JavaScript features in Acrobat 9. See what the all-new Acrobat DC can do for you.

Download a free trial of the new Acrobat.

Conditional execution and Acrobat JavaScript

Learn about Conditional Execution, one of the most important features of any programming language, including Acrobat JavaScript.

By Thom Parker – January 12, 2010

 

One of the most important features of any programming language is the ability to make decisions, called Conditional Execution. It is the ability to execute a piece of code depending on some condition. In Acrobat JavaScript, the primary element of conditional execution is the "if" statement. While there are others, none is as generic and widely used as the "if" statement.

Writing an "if" statement

In computer programming, all decisions are made by comparing values. For example, on an order form we might want to give the customer a discount if they spend more than $100. To express this idea in English, in the context of our form we might say "If the Subtotal is greater than 100, then set a 10% discount." In this case, we are comparing the value of the order’s subtotal to the constant value 100, then placing a percentage of the subtotal into the discount field if the result of the comparison is true. The Acrobat JavaScript code for performing this conditional calculation is exactly the same as our English statement, only it is expressed in JavaScript syntax. The following code is placed in the calculation event for the discount field:

var nSubTotal = this.getField("subtotal").value;
if( nSubTotal > 100) event.value = nSubTotal * 0.10;

The first rule of writing conditional statements is to clearly and simply express the complete set of conditions in English. The conditions must make sense, not conflict with one another, and be testable from concrete values available to the code.

Problems with conditional execution are a very common issue posted to the forums. All too often, the root problem is revealed as an unclear and/or conflicting statement of the necessary conditions. It can’t be stated too often or too strongly that the first step of writing conditional code is to state the conditions clearly and make sure they do not conflict. As we’ll see, this is especially important for complex conditions.

Now let’s rewrite the "if" block code (shown above) in pseudo code so we can better understand how it’s constructed.

if(  ) 

This pseudo code shows the simplest way to write a decision block. This particular "if" block can be divided into two parts-- the condition, and the code that is run when the condition is met. The condition is a short piece of code that results in a true or false value, and it is called a Boolean Expression.

Value comparisons and the Boolean expression

Boolean Logic is a system of mathematics that deals with true and false values, called Boolean values. As we will see, Boolean Logic is actually very simple and it is a key element of computer programming. A Boolean expression is a piece of code that operates on, and/or results in, a Boolean value. Boolean expressions are created using the comparison and Boolean operators. In our previous example, the condition is the expression:

nSubTotal > 100

where the operator is the Greater Than, ">", comparison operator. If nSubTotal is greater than 100, the expression returns a value of True; otherwise it returns a value of False. The other comparison operators are: Less Than; "<", Equals to; "==" and Not Equals; "!=". There are also compound-comparison operators that combine Greater Than and Less Than with Equals to; "<=" and ">=". All these comparison operators return Boolean values. Most of the time, they will be the starting point for a Boolean expression, converting values from the form into true or false values that will be used to make decisions with an "if" statement.

It’s important to note that these comparison operators work for both number and text values. This is important because many of PDF form fields return text values. For example, both radio buttons and checkboxes export a text value. The checked or selected value is set by the form designer, but the unchecked/unselected value is always "Off." We can use this value in a Boolean expression to detect and make decisions based on the unchecked checkbox, or the unselected Radio button group.

The code below is used in a form-level validation script to let users know they have to check "I Agree" before submitting a form:

var cAgree = this.getField("AgreeCheck").value;
if( cAgree == "Off" ) app.alert("You must select ‘I Agree’ before continuing");

So now we’ve seen how to create a simple Boolean expression by using a comparison operator to compare two values to one another. But what do we do if our condition is more complex? For example, what if we need to test that a field value is within a range between two values, or something even more complex? To handle these situations, we need to write a Compound Boolean expression.

Compound Boolean expressions

Complex Boolean expressions are created by combining simple expressions with the Boolean operators. The basic Boolean operators are: And; "&&", Or; "||", and Not; "!". Along with grouping sub-expressions in parentheses, these operators can be used to create conditional expressions for almost any situation you will ever need. In fact, as previously stated, there is a whole branch of mathematics devoted to studying Boolean expressions. But for our purposes here, and for the majority of situations you’ll be dealing with, we can stick to the basics.

To write a complex expression, it first has to be expressed in English. In our first example, a discount was created based on the subtotal being greater than 100. Let’s modify that condition to this: "If the subtotal is greater than 100 and the subtotal is less than or equal to 200, then apply a 10% discount." This conditional contains a second condition tied to the first part with "AND." The "AND" means both parts have to be true in order for the total expression to be true. The implementation is exactly as stated.

event.value = 0;
// Initial discount value var nSubTotal = this.getField("subtotal").value;
if ( (nSubTotal > 100) && (nSubTotal <= 200) ) event.value = nSubTotal * 0.10;

This code is nearly the same as the first example. The only difference is the addition of the second condition. But there are a few very important details here worth noting. The first is the use of the compound comparison operator "<=". Using this operator has made our job much easier because it’s packing two comparisons into one. The sub-expression returns true for two conditions, subtotal is less than 200 and subtotal is equal to 200. Without the compound comparison operator, we’d have to write the expression with three conditions.

The second detail of note is that the two comparisons are grouped using parentheses. This is important for two reasons. First, it makes reading the code easier, and second, it ensures proper execution of the expression. Strictly speaking, the parentheses are not always necessary, but unless you are an expert at precedence of operator execution, you should always group the sub-expressions you want to execute as a single entity. Otherwise, the JavaScript engine may just decide to do the execution differently.

And finally, we get down to the "&&". This operator only returns true if both conditions are true, so this is where we need to make sure our conditions make sense. You can very easily write nonsensical expressions. For example, here’s a small change to our Boolean expression.

(nSubTotal < 100) && (nSubTotal > 200)

There is nothing wrong with this code as far as the Acrobat JavaScript engine is concerned. It will not complain, but obviously this expression will never be true. A number cannot be both less than 100 and greater than 200. This may seem silly, but it is surprisingly easy to set up unrealistic and conflicting conditions.

To stretch this concept a bit further, let’s add an additional layer of complexity by also applying the discount when the customer is a member of our company website, as indicated by a checkbox on the form. So, our statement of conditions is now: "If the subtotal is greater than 100 and the subtotal is less than or equal to 200, or if the members checkbox is checked, then apply a 10% discount." The "if" statement is shown below, but for brevity, the supporting code is not included; and to make the groupings more obvious, the parentheses are color-coded:

var bMember == this.getField("MemberCheck").isBoxChecked(0);
if ( ( (nSubTotal > 100) && (nSubTotal <= 200) ) || bMember) <. . .>

Notice that our original two conditions are grouped, making them a single entity in the expression and allowing us to use the original expression unchanged. Expressions and sub-expressions can be nested within parentheses as deep as necessary to create the condition. The total condition here is true if either the checkbox is checked or our original set of conditions is true.

The final logical operator "!" is used to invert the return value of a sub-expression. Let’s change the expression to only apply the discount when the customer is not a member. So here’s our new statement of conditions: "If members checkbox is not checked and the subtotal is greater than 100 and the subtotal is less than or equal to 200, then apply a 10% discount." In this case, we are not using an OR operation. Instead, we are adding to the AND of the original conditions. Here’s the if code:

if ( !bMember && (nSubTotal > 100) && (nSubTotal <= 200) )
<. . .>

Now we’re ready to move on to the next level of complexity, setting up multiple conditions.

Multiple conditions

All conditional expressions have two results. The condition is met, or it’s not met. So far, we’ve only looked at running code for the situation where the condition is met. But we can also run code for the negative result by constructing the "if" statement with an "else" section, like this:

if(  )  else 

Using this structure, we can rewrite the first example to apply a zero discount if the condition is not met:

var nSubTotal = this.getField("subtotal").value;
if( nSubTotal > 100) event.value = nSubTotal * 0.10;
else event.value = 0;

But, the "else" is for more than running the negative result code. It provides for default execution. The "if" block can contain multiple conditions, each with its own section of conditional code. If none of these conditions is met, then the "else" code is run, making sure we have a way to cleanly finish things off, i.e., perform a default action.

For example, say we need to apply different discounts for different purchase amounts. Our new condition statement is then: "If the subtotal is greater than $200, then apply a 20% discount, else if the subtotal is greater than $100 apply a 10% discount, else if the subtotal is greater than $50 then apply a 5% discount, otherwise no discount is applied." The multiple condition "if" is structured with "else if" sections like this:

var nSubTotal = this.getField("subtotal").value;
if( nSubTotal > 200 ) event.value = nSubTotal * 0.20;
else if( nSubTotal > 100 ) event.value = nSubTotal * 0.10;
else if( nSubTotal > 50 ) event.value = nSubTotal * 0.05;
else event.value = 0;

We can build "if" blocks with as many "else if" sections as necessary, or none at all. The "else" section is optional as well, but if there is one there can only be one, and it must be last. The "if" section is of course mandatory and it must come first.

For each condition in the code above, the discount is actually applied to a range of values. For example, the 10% discount is applied for purchase amounts between $100 and $200. But because these amounts are a progression, we can make the code more efficient and easier to write by starting with the largest amount first and working down. It’s always a good idea to try to arrange the conditions so they create the most efficient and sensible flow through the logic. If none of the conditions is met, then default code in the "else" section sets the discount to zero.

Running multiple lines of code

All the examples shown so far run a single line of code for the conditional execution. I’ve done this for simplicity, but of course we can run any amount of code in a condition. To do this, the code needs to be surrounded by curly braces "{}", called block delimiters. Any code inside the curly braces is grouped into a single entity by the JavaScript engine. This same grouping structure is used with several different types of code flow operators in the JavaScript language, such as functions and loops. Here’s a modification of the first example that not only sets the discount, but also displays a popup message to the user.

var nSubTotal = this.getField("subtotal").value;
if( nSubTotal > 100) {
	event.value = nSubTotal * 0.10;
	app.alert("Congratulations, you get a discount",2);
} else {
	event.value = 0; app.alert("Sorry, no discount for you",2);
}

More "if"

It’s important to understand that the "if" statement is purely Core JavaScript. I’ve presented it here in the context of Acrobat JavaScript and specifically for creating conditional calculations. However, the concepts presented (the "if" structure and Boolean expressions) are very general-purpose and widely used throughout all implementations of JavaScript, as well as many other languages including C, Java, and ActionScript. You can find out more from a Core JavaScript Reference.

My favorite Core JavaScript reference is "The Definitive JavaScript Guide" from O’Reilly.

The official Core JavaScript web reference is here:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference

You can find an example PDF that uses the "if" statement in conditional calculations here:
http://www.pdfscripting.com/public/47.cfm#CondCalcs
And if you look around at just about any sample code, you’ll find examples of "if" statements.



Products covered:

Acrobat 9

Related topics:

JavaScript

Top Searches:


5 comments

Comments for this tutorial are now closed.

Thom Parker

12, 2015-07-18 18, 2015

Judy, use this.getField() to get the values of the fields you need to sum. Like this.

event.value = this.getField(nField).value + this.getField(mField).value + this.getField(zField).value;

Judy

5, 2015-07-15 15, 2015

I am trying to write an if else statement: if the value of xField is 0, enter yField value; else enter the sum of (nField, mField, zField)

I got the sum part to work yesterday, but I didn’t save it and when I went back to the field it had reset to an uncalculated field. Now I can’t get it to work again.

I’m using the following script:

var nPay = this.getField(“xField”).value;
var nHours = this.getField(“yField”).value;

if (nHours == 0) event.value = nPay;

else event.value = Sum (nField, mField, zField);

Thom Parker

4, 2014-11-17 17, 2014

i s

The key to debugging a script is to break it down into parts and check each part individually. For example, the first thing the script does is acquire the values of the source fields. Are these values being returned correct? What are the values?  Is the value of a unchecked check box really “off”.

Watch this video:
http://www.pdfscripting.com/public/images/Free_Videos/BeginJS_Console_Alt.cfm

i s

11, 2014-11-14 14, 2014

Trying to have a code that populate a dropdown based on values in check box and another dropown, i have the code as calculation script in in dropdown2 but not going anywhere, Here is my code

var v=this.getfield(“drop1”).value;
var g=this.getfield(“Box1”).value;
var a=his.getfield(“Box2”).value;
if ( (g!==“off”) && (v==“Finance”) ){
  event.value=“934-0000-000000-001-00-000”;}
else
if ( (a!==“off”) && (v==“Finance”) ){
  event.value=“534-0000-000000-001-00-000”;}

any suggestion?

Thom Parker

5, 2014-11-11 11, 2014

Matt,
  Since your action (hideing/showing) is driven from two sources, the best location for a script is a calculation event. It doesn’t really matter on which field you put the script because calculations all happen at the same time, but a good choice is one of the fields being hidden/shown.  Have the script acquire both values and then set the hidden attribute on both fields.

Matt Simmons

9, 2014-11-10 10, 2014

Hi, Im trying to write code that will display one of two form fields depending on a)a checkbox being ticked and b) one of two values in a dropdown list. i.e.
do i like animals? tick checkbox
which animals do i prefer 1) cats? 2) dogs?
field to display will have an image of a cat or a dog or no image if the checkbox isnt ticked.

these arent the real choices but the simplest way I could explain it.

Thom Parker

5, 2014-09-29 29, 2014

Allen,
  The easiest approach is to create a calculation script based on the code shown in the “Multiple Conditions” section of the article above. Just change the value returned in event.value from a number calculation, to plain text.

Allen Jones

4, 2014-09-26 26, 2014

Greetings-
I’m trying to create a text box on a PDF using Adobe Pro that will return one of six possible phrases based on the number value of a separate box. Please help

Lori Kassuba

3, 2013-12-13 13, 2013

Hi m fernandez,

Please post your question here and select the JavaScript category so our experts can help you interactively:
http://answers.acrobatusers.com/AskQuestion.aspx

Thanks,
Lori

m fernandez

10, 2013-12-09 09, 2013

Does anyone have any suggestions on how to do the following:

I have created two dropdown fields:  1) Current Living Situation and 2) Housing Type.

If would like the Housing Type field to default to NA on its dropdown list if a person enters anything other than “rental housing” on the current living situation field. I also want the Housing Type field to become read only after the it defaults to NA. It want it to revert if the user changes their choice in the Current Living Situatio dropdown.

Any help would be appreciated.

Lori Kassuba

6, 2013-05-06 06, 2013

Hi Demetrius,

Can you please please post your form question here, so folks can help you interactively?
http://answers.acrobatusers.com/AskQuestion.aspx

Thanks,
Lori

Demetrius

8, 2013-04-28 28, 2013

Hello,
I have Acrobat Pro X.  I am working on a particular form page that needs to have a formula that is more than just adding up various cells to obtain a total of several numbers.  I have 2 particular boxes that I want to calculate.  Here is what I am trying to do:

I want to have a javascript code that reads one box or cell I named “H Totals 1-5” to see if the dollar amount is $5,000 or less.  If the amount is equal to or less than $5,000 the amount will not appear in another box or cell I named, “Column H Total.”  If the dollar amount in “H Totals 1-5” is over $5,000 I want that amount to appear in the box or cell “Column H Total” multiple that amount by 2% and put that amount in another box or cell I named, “Imputed Income.”  For example, if the amount is $5,100 that amount would then appear in “Column H Total” is $102 (2%) of $5100. 

Can someone please help me with creating the code that will go in the “Custom” Javascript box inside of the Adobe Acrobat X forms page and email it to me. 

Thank whoever will help me.  I truly would appreciate your assistance. 

Thom Parker

6, 2012-10-20 20, 2012

What value are you hoping to acquire from app.alert ? 

Please ask this question on the forums and explain what you mean by “it isn’t working”

Angela Standridge

3, 2012-09-10 10, 2012

Hello,

I’m trying to create a PDF form with a leave use or loss calculation. Based on what is provided I’ve come up with this formula:

var nSubTotal = this.getField(“Annual Leave Rate”).value * this.getField(“Number of Pay Periods”).value + this.getField(“LAPreviousBalance”).value - this.number (“240”).value;
if( nSubTotal < 0 ) event.value = app.alert(”:o(”);
else if( nSubTotal = 0 ) event.value = app.alert(”:o(”);
else if( nSubTotal > 0 ) event.value = nSubTotal.value;

But it isn’t working.

Any help would be greatly appreciated.

Thank you for your time.

Angela S.

Comments for this tutorial are now closed.