ExTENDING Acrobat FO RMS
WITH JAVASCRIPT
JOHN DEUBERTExtending Acrobat
Forms with
JAVASCRIPT
JOHN DEUBERTExtending Acrobat Forms with JavaScript
John Deubert
Copyright © 2003 by John Deubert
“This Adobe Press book is published by Peachpit Press.
For information on Adobe Press books, contact:
Peachpit Press
1249 Eighth Street
Berkeley, CA 94710
510/524-2178 (el) 510/524-2221 (fax)
To report errors, please send a note to
[email protected]
Peachpit Press is a division of Pearson Education
For the latest on Adobe Press books go to
httpu/www-adobe-comladobepress
Editor: Becky Morgan
Production Coordinator: Lisa Brazial
Copyeditor: Sally Zahner
‘Compositor: Maureen Forys
Interior Design: Mimi Heft
Indexer: FiteCrystal Communications
‘Cover Design: Hugh D’Andrade
Notice of Rights
Al rights reserved. No part of this book may be reproduced or transmitted in any form by any
‘means, electronic, mechanical, photocopying, recording, or otherwise, without the prior writ-
ten permission of the publisher. For information on getting permission for reprints and
‘excerpts, contact permissions@peachpiticom,
Notice of Liability
‘The information in this book i distributed on an “As Is” basis, without warranty. While every
precaution has been taken in the preparation of the book, neither the author nor Peachpit
Press, shall have any liability to any person or entity with respect to any los or damage caused
or alleged to be caused directly or indirectly by the instructions contained in this book or by
the computer software and hardware products described init.
‘Trademarks
‘Throughout this book, trademarks are used. Rather than put a trademark symbol in every occur-
rence ofa trademarked name, we sate that we are using the names in an editorial fashion only
and to the benefit ofthe trademark owner with no intention of infringement of the trademark.
Adobe Acrobat and Adobe Photoshop are tradematks of Adobe Systems Incorporated.
ISBN 0-321
238-8
987654321
Printed and bound in the United States of AmericaDedication
For Barbara, always.Acknowledgements
It takes a whole village to raise a book; the author gets to put his or her name
on the cover, but itis everyone together who actually creates the creature of
bound paper that sits on a bookshelf. I would like to thank several people
who were part of the creation of this particular paper beast: in particular, my
editor, Becky Morgan, who never, not once, boxed my ears for proposing
radical changes to the book and asking when the deadline was. Production
coordinator Lisa Brazieal, who made sure that the book was a pleasure to
behold. There would also be no book without copyeditor Sally Zahner
(“She of the Eagle Eye"), compositor Maureen Forys, and indexer Emily
Glossbrenner. I also thank Hugh D'Andrade, who designed the beautiful
cover.
‘There are many other people at Adobe and at Peachpit Press whose work
went into this book and I thank them all.Table of Contents
1: Welcome to JavaScript! .
What Is JavaScript? .
Our First JavaScript
‘Attaching a JavaScript toa Form Field
JavaScript Objects
JavaScript Program Syntax .
JavaScript Errors
JavaScript Comments
Acrobat JavaScript Guide
Using Your Own Text Editor
2: Page and Document JavaScripts
The Project ..
Document JavaScripts
Global Variables
Document Action JavaScripts
Page Action JavaScripts
The Project ..
The JavaScript
Approaching the Problem
‘The Code
Customization Notes
4: Checking Acrobat Version .
The Project 34
The JavaScript ..... 35
Approaching the Problem 35
“The Code
‘Testing the Code .
Customization Notes
‘Testing for Viewer Type...
5: Calculating Form Fields
The Project ....wl
TABLE OF CONTENTS
The JavaScript
Creating a Calculated Field
The Item Calculations
Calculation Order .
Enhancements ...
Hiding Zeros ...
“Global” Tax Rate .
6: Auto-Entering Form Data ..
The Project .
‘The JavaScript
‘The Approach :
Combo Box Export Values ..
Creating the Price List Array
7: Roll-Over Help
The Project .
The JavaScript a
The Approach a
The Code 7
Enhancement . .
‘The Document JavaScript
New Form Field JavaScript
8: Dynamic Form Fields
Project 1: Attaching the JavaScript to a check box
The JavaScript ceteeeeeeee cee
Approaching the Problem ............... cece 81
Project 2: Attaching the JavaScript to a combo box ..... 85
The JavaScript
JavaScripts for Other Control Types.
List Box ..
Radio Buttons
Buttons and Text Fields
9: Dynamic Controls with Templates.
The Project .
The JavaScript
Creating the Templates .
The Check Box JavaScriptTABLE OF CONTENTS
Keystroke JavaScripts
The JavaScript
‘Additional Regular-Expression Metacharactrs
11: Field Validation
The Project
The JavaScript
[Approaching the Problem
‘The Name Field
Serial Number Field
Enhancements.
Blank Fields
Rejecting Bad Input
Regular Expressions from the Web
More Metacharacters ...
12: Formatting Text Fields
The Project .....6000++
The Format Panel .
Parentheses in Regular Expressions.
The JavaScript...
Validation vs. Formatting
13: Alerts and Dialog Boxes.
Displaying Alerts: app.alert
Alert Icons .
Alert Buttons
Asking a Question: app.response ..
The Project
“The Close Form Script
‘The Submit Order Script
14: JavaScript Functions
JavaScript Functions
Creating a Function
Project 1: Functions in Document JavaScriptsvill TABLE OF CONTENTS
Project 2: Two Buttons Sharing Code ..........
Approaching the Problem
‘The JavaScripts ......
15: Creating Pop-Up Menus ..
app.popUpMenu .....
The switch Command
The break Command
‘The Project
The JavaScript.
The Other Buttons
Customization Notes :
Functions in case Code ..
Pop-Up Menu User Interface
16: Interacting with Databases ..
Database Basics
SQL...
ODBC ...
ADBC .
Database Objects
The try and catch Commands
SQL in a Form
17: Reading and Writing a Database .
Project 1: Browsing a Database
‘The JavaScripts ....
‘The Document JavaScripts
Page Open Script
Form Field Scripts
Project 2: Adding New Data
The SQL INSERT Command
The Script ..
Other Commands .
18: Generating Reports ..
‘The Report Object.
Creating a Report. .
Creating a Report Object.
Report Object Properties.
Report Object MethodsTABLE OF CONTENTS ix
The Project ..
The JavaScript ...
Customization Notes .
19: Where Now? ...
Congratulations!
‘What Now? .....
Acrobat JavaScript Resources
Internet ..
Learning JavaScript
Internet
Regular Expressions
Internet
Form Processing .
A: Object Reference ......++
B: Regular Expression Metacharacters .......22002s0eeeeeeeeseees 249
Index .Introduction
Welcome to the Land of Acrobat JavaScript.
This book will teach you how to extend the abilities of your Acrobat forms
by adding JavaScript programs to form fields, pages, and to the documents
themselves. It is hard to exaggerate the extent to which JavaScript can
enhance your forms’ appearance, functionality, and interface; suffice it to
say that even a basic knowledge of JavaScript opens a very wide range of
capabilities to a form designer.
JavaScript is very fun, very powerful stuff, If you have already designed a
range of forms and are looking to add such things as connection to data-
bases, sophisticated user-interface features, automatic form-field formatting,
and dynamically visible form fields, Acrobat JavaScript is the means by
which you do this.
This book will show you how.xl EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Book
What this book is.
This book is a non-programmer’s guide to adding specific features to your
Acrobat forms using JavaScript. If you are a form designer with good Acrobat,
experience, but have never written a line of JavaScript, C, or other program
‘ming code before (and were pretty sure you never wanted to do so), then
this book is for you. We shall introduce programming concepts as we learn
how to add specific enhancements to your forms; for example, we talk about
arrays while adding a price table to a form, case statements while creating a
pop-up menu, if-else commands while checking the version of the user's
Acrobat viewer.
This book is not a complete reference to the JavaScript Language or to the
JavaScript capabilities of Adobe Acrobat; itis a non-programmers intro-
duction to both. Having read this book, you will be in an excellent position
to read a more formal reference on the complete JavaScript language and
to make use of Adobe's documentation on Acrobat JavaScript.
With one exception, all of the examples in this book will work with either
the Mac or Windows version of Adobe Acrobat; the exception is database
connectivity, which exists only in Acrobat for Windows. Illustrations are
taken from both platforms; thankfully, the Acrobat user interface is nearly
identical in the Mac and Windows versions.
Most of the scripts presented will work for either Acrobat 4 or Acrobat 5;
some require the later version. Restrictions are noted when appropriate.
1 am assuming you have reasonable experience in designing and creating
Acrobat forms. We won't be discussing the mechanics of creating form
fields or the differences among the different types of form fields. [ also
assume you are very comfortable with your computer environment.
How to use this book
The first two chapters of this book present basic information and terminol-
ogys and therefore must be read before you continue. Chapter 19 isa list of
resources. The remaining chapters may be used in two ways:
@ You can read Chapters 3 through 18 in order, proceeding as you would
through any other book.
Overall, this is probably the more effective way to approach the book,
since chapters cannot help but refer to each other to some extent.LE) INTRODUCTION xilt
When you finish, you will have accumulated quite a sum of useful
techniques and information for using JavaScript in Acrobat.
= You can read Chapters 3 through 18 on a topic-by-topic basis, reading
those chapters that apply to a specific feature you want to add to your
forms.
Thus, if you need to add roll-over help to a form, you can skip ahead to
Chapter 7 and see how to do it. The chapters have all been written to
be somewhat autonomous; you don't need to read them sequentially to
use the information. Some chapters will insist on being read as a unit
(for example, Chapters 10, 11, and 12 on form field validation and for-
matting must be read as a set to be useful) and other chapters will send
you elsewhere in the book for background information. By and large,
however, the chapters are intended to be semi-independent parts.
All the chapters, however, assume you have read Chapters 1 and 2; start,
with those.
Online Resources
The Web site
Most chapters in this book are built around a sample form, to which we add
JavaScripts that accomplish that chapter's goal. The form files for all the
chapters are available free for the downloading on the Extending Acrobat
Forms Web page: http://www.acumentraining.com/acrobatjs.html
Here you will find all the forms that appear in the book. Fach form comes
in two versions:
= The complete form, with all JavaScripts in place and all the features
working
= A “raw” version of the form, with that chapter's JavaScripts missing
For example, for Chapter 3, you will find two form files:
(Ch03_Examplel pdf and Ch03_Example|_raw.pdf.
Each chapter gives step-by-step instructions for adding the JavaScripts to
the raw version of the form. If you prefer to see the JavaScript already in
place, just follow those same numbered steps with the complete file; when
you get to the “type in the JavaScript” step, you will find the script already
in place.xly EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Acumen Journal
You can find additional information on Acrobat JavaScript in my free,
monthly newsletter, the Acumen Journal. Every month, the Journal has an
article on Acrobat; every second month, that Acrobat article covers some
topic in JavaScript that is specifically intended for readers of this book. The
article presents information on how to do something useful in JavaSc
adds to your knowledge of the JavaScript language. These articles explicitly
assume you have read this book. (Other people can also read the articles, of
course; they will simply have to know as much as you will know upon fin-
ishing the book.)
The Acumen Journal is available at: http://www.acumentraining.com/
ajournal.asp.
‘There is also a link to the Journal on the Extending Acrobat Forms Web page
mentioned above.Welcome to
JavaScript!
Life is full of threshold phenomena.
Periodically in life, you learn something that broadens your world immeasur-
ably, revealing an expanse of new experience, problems, opportunities, play,
and work. Whole worlds that had invisibly surrounded you suddenly appear,
providing a new space to explore. Reading, sex, driving, children, all bring with
them concerns, interests, and interactions that had been previously inaccessible
and unsuspected.
In its own small way, learning JavaScript will be just such a threshold event
in your professional life. If you've been working with Acrobat for any length
of time, you've probably gotten pretty good at it and have become quite
comfortable at creating forms, adding music, creating slide shows, and all
the other features Acrobat offers.
This book introduces the New World. A knowledge of JavaScript allows you
to do things within Acrobat that far exceed what you've done so far: You can
interface with databases; add your own pop-up menus; create forms with
sophisticated, interactive interfaces; and implement form fields that can look
up prices and other data. These are only a few of the things you can do
within your Acrobat documents using JavaScript. The extent to which you
can manipulate your Acrobat files is vastly greater with JavaScript skills than
without.EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Hence, this book.
Here you will learn how to accomplish a variety of useful tasks in Acrobat
using JavaScript. Along the way, you will learn a great deal about JavaScript,
programming, and Acrobat.
What You Should Know Already
This book assumes you have reasonably extensive experience in working
with Acrobat and creating Acrobat forms. In particular, I assume you know
how to create forms in Acrobat; you should be able to create a form field,
set its properties, and assign actions to it. If you feel vaguely uneasy about
any of these tasks, you may want to run right off and buy my earlier Adobe
Press book, Creating Adobe Acrobat Forms. Buy two copies!
Beyond that, this book does not assume any knowledge of programming; you
will learn the programming skills you need as we proceed through our examples
What Is JavaScript?
JavaScript is a programming language. The term programming language
often induces a case of jitters in newcomers, but, conceptually, it’s not very
scary: A programming language is a language that is used to describe the
steps involved in carrying out some task. In Acrobat, these tasks include
moving to a particular page of a document, sending data to a database,
and calculating a form field value, Carrying out the steps described by a
JavaScript is referred to as executing the program.
Asa programming language, JavaScript’s most significant characteristic is
that it’s sufficiently simple that many applications use it as their native
scripting language. All Web browsers can interpret JavaScripts embedded in
Web pages, and, particular to our topic, Acrobat can execute JavaScripts
attached to form fields, pages, and PDF files.
Like any language, JavaScript has its own vocabulary (words that have mean
ing) and syntax (rules by which you make statements with those words).
Learning JavaScript, therefore, has much in common with learning a human
language, such as Spanish or German, only it’s much easier. JavaScript is vastly
simpler than any human language: There are no metaphors, no literally
nonsensical idioms, no synonyms, no subtle shades of meaning. Just very
precise statements telling Acrobat to do something specific.2 | WELCOME TO JAVASCRIPT! 3.
JavaScript in Acrobat
Acrobat allows you to create four different kinds of JavaScripts:
= Form Field JavaScripts are attached to form fields. Acrobat executes the
script when a particular event occurs in that form field, such as a but-
ton click. Most JavaScripts in Acrobat are attached to form fields.
© Page JavaScripts are executed when the user moves to or leaves a partic~
ular page in the Acrobat document.
= Document Action JavaScripts are executed when the user opens, closes,
saves, or prints a document.
= Document JavaScripts are executed when the Acrobat document opens.
We shall talk about Page, Document Action, and Document JavaScripts in
Chapter 2. For now, let’s look at how you type in and use a Form Field
JavaScript.
Our First JavaScript
(Files: ChO1-Example1.pdf, ChO1.Example1Raw.pdf)
Let's start exploring our new world by adding a simple JavaScript to the
form field in Figure 1.1.
‘This form consists of a set of flash cards that are intended to be printed
double-sided and then used to quiz students on vocabulary terms. Our PDF
file has only a few flash cards; each card has a button that takes users to an
order form they can use to purchase the complete set of cards. We are going
to add a JavaScript to the Order Form button that takes the user to the
order form, located on the last page of the Acrobat file (Figure 1.2).
Figure £1 We shall add a
JavaScript to this form, attached
to the Order Form button’s
‘Mouse Up event.4 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Order Form
Hove them!
Please send me ___ copies of Mr. Figure 1.2 The JavaScript
Smarty's Flash Cards for me and associated with the Order Form
my family. button takes the viewer to the
final page in the Acrobat docu-
‘ment, which is an order page.
As will be true throughout this book, there are two versions of this form on
the book's Web page:
= ChO1.Example!_paf is the full form, complete with all relevant
JavaScripts.
= ChO1.Example1Raw.pdf, the “raw” version, lacks the chapter's JavaScripts
so that you may type in the JavaScript yourself if you wish.
Attaching a JavaScript to a Form Field
As a reminder of something you probably already know, let’s step through
the process of attaching a JavaScript to a button, in this case our Order
Form button.
To attach a JavaScript to a button:
Start with the form open in Adobe Acrobat.
4. Click on the Form tool
Acrobat will display all of the form fields on the current page as a set of,
rectangles. Note that in our case, there's only one form field (Figure 1.3).
1. Axolot
a. An Incan pedestal Figure 1.3 Our flash
bb. A type of salamander card form has only one
An altar implement form field on each page:
4d. An ancient constellation a button, btnOrderForm,
that takes the user to the
‘order form page.2 | WELCOME TO JAVASCRIPT!
Form Field Events
‘AS shown in Figure 1.4, there are six form field events to which you can attach an
action:
= Mouse Down occurs when the user depresses the mouse button with the pointer in
the form field.
=| Mouse Up occurs when the user clicks on the field and then releases the mouse
button with the mouse pointer still in the field.
= Mouse Enter occurs when the mouse pointer first enters the form field.
= Mouse Exit occurs when the mouse pointer leaves the form field.
= On Focus occurs when the user clicks on or tabs Into the form field, so that it
becomes the target for keyboard or other input.
= On Blur occurs when the user tabs out of a form field or clicks on some other form
field, so that our field is no longer the target for user input. (Blur is the opposite of
Focus, of course.)
‘The Field Properties dialog box, in Figure 1.4, lets you associate one or more Acrobat
‘Actions (a JavaScript action, in our case) with any of these events.
2. Double-click the Order Form button.
Acrobat will present you with the Field Properties dialog box (Figure 1.4).
Click the Actions tab. We want to attach a JavaScript action to the Mouse
Up event for this button.
3. Select the Mouse Up action and click the Add button.
Figure 1.4 In the
button's Field
Properties dialog
box, we want to add
an action to the
Mouse Up event.@ EXTENDING ACROBAT FORMS WITH JAVASCRIPT
You will now be looking at the Add an Action dialog box (Figure 1.5)
Here is where we tell Acrobat what action we want to attach to the
Mouse Up event.
Figure 15 The Add
‘an Action dialog box
is where we attach
Acrobat actions to
events. We shall
be attaching the
JavaScript action to
the Mouse Up event.
4. In the Type pop-up menu, select JavaScript and then click the Edit button.
Acrobat will present you with the JavaScript Edit dialog box, which
contains a simple text editor (Figure 1.6). This is where you type in the
JavaScript that should be associated with the Order Form button.
Figure 6 The JavaScript
Edit dialog box provides a
simple textediting field into
which you can type your
JavaScript code.
5. Type your JavaScript into the text field of this dialog box.
In the case of our order form, the JavaScript is a two-line program that
moves the user's view of the document to the page containing the order
form and then causes the user's computer to beep: Type these lines into
the text-editing field exactly as above, making sure to match upper- and
[Sette curent lowercase,
page number to 6 [this.pageNum = 6
ffevaerober to —|_—{app. beep1 | WELCOME TO JAVASCRIPT!
The first line of code says, “In this document, set the current page
number to 6.” The second line tells the Acrobat application to beep.
6. Click the OK buttons of the JavaScript Edit, Add an Action, and Field
Properties dialog boxes to return to the Acrobat form.
You are now looking at the Acrobat flash card page with the Form tool
still selected, as in Figure 1.3,
7. Click the Acrobat Hand tool &)).
You are now back where you started.
8. Try it out: Click the Order Form button, and Acrobat will move to the
order form page and then beep.
JavaScript Objects
Our two-line JavaScript makes use of two JavaScript objects. A JavaScript
object is the representation of some piece of data within your JavaScript
program. Before your program can manipulate or examine a form field, it
must first create an object that represents that field. Most of the things you
can manipulate in JavaScript (pages, signatures, database connections, and
so on) are represented in your program as objects.
In our sample program, this refers to a Doc object.A Doc object represents
an open Acrobat file to your JavaScript program; you use this object to
change pages, save the document, and otherwise manipulate the document
from within your program. The word this in our sample JavaScript refers
particularly to the Acrobat document in which our JavaScript resides (the
flash cards file, in our case); think of it as short for this document.
Program vs. Script vs. Code
Here are some closely related terms that we'll be using throughout this book.
Program is @ general term for a series of instructions that detail for a computer how
to carry out a particular task. In general, a program Is a stand-alone set of instruc-
tions, such as an application.
‘A Script is a program that is intended to manipulate another program. JavaScript Is a
scripting language, because you use it to control the behavior of another program,
‘such as Acrobat or Internet Explorer.
Code Is the term applied to the set of instructions that make up a program. Your
JavaScript program is made up of JavaScript code.
18 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
‘The word app is an App object, a reference to the Acrobat application being
used to view the current document. You use an App object to tell the
Acrobat application to do something: open a file, put up an alert dialog box,
or, in our case, beep.
Commonly used JavaScript object types include:
= Annot represents an annotation (for example, a “sticky note”) in the
current document.
= App represents the Acrobat application being used to view the current
document.
= Connection represents a connection to an external database.
= Doc represents the current (frontmost) open Acrobat document.
= Field represents a form field.
= Sound represents a sound embedded in the current document.
Object properties
JavaScript objects are analogous to physical objects in the world around us,
such as books, vases, and dogs. Every real-world object possesses a set of
characteristics that define it (such as, for a dog, color, tail length, and num-
ber of fleas).
Which Acrobat?
‘There are currently three applications that are routinely used to view Acrobat files:
= Adobe Acrobat Reader is the free application that lets you view and print PDF files.
= Adobe Acrobat Approval is a relatively inexpensive product that lets a user view, print,
and annotate POF files and fully fill out Acrobat forms.
= Adobe Acrobat (“the full Acrobat”) is what you use to add features to PDF files:
rearrange pages, create form fields, specify start-up properties, and, specific to our
Purpose, attach JavaScripts to form fields.
‘Only with the full Acrobat can you create form fields and attach JavaScripts to form fields
and pages. Most of the JavaScripts you write will work correctly with any of the three
‘Acrobat viewer packages. There are exceptions (the Reader is particularly limited), but
they are relatively few.
In this book, | will refer to all three of the Acrobat viewers as “Acrobat” except for cases
‘where they behave differently.1 | WELCOME To JAVASCRIPT!
The characteristics of a JavaScript object are referred to as that object’s
properties. These are elements of an object that our JavaScript programs
can examine and change as needed. Each type of object has a set of prop-
erties that characterize it; for example, Doc objects have, among other
things, a title, a current page number, an author, and a number of pages
(see Table 1.1).
Table 1.1 Document Object Properties (Partial)
author String The author of the document
filesize Integer The size of the PDF file, In bytes
numPages Integer ‘The number of pages in the document
pageNum Integer ‘The page number currently visible to the user
title String ‘The name of the document
The phrase this. pageNum addresses the pageNum property of the Document
object; this property is the page number the document is currently display-
ing to the user. Our program moves the user to the order form page by
setting the current document's pageNum property to the order form’s page
number:
this.pageNum = 6
| Data Types
The Data Type column of Table 4.4 lists the type of information associated with each of
the properties it lists. Computer programming, Including JavaScript, uses special terms to
Precisely describe types of data. Here are the terms commonly used in JavaScript:
= Integer Is @ whole number, such as 1, 2, 87, or -6293.
= Floating Point is a number with a fractional part, such as 1.7, 842.9011, 1024.0.
Note that the fractional part may be zero, as in 1024.0; in this case, the floating point
number has the same value as an integer, though internally it is still a floating point
number. Floating point numbers are often referred to as floats.
= Boolean is an entity that can have two values: true or false. Boolean data are used to
| describe characteristics that can have only two states. (For example, the spayed prop-
erty in our dog object is a Boolean value; a dog either is or Isn't.)
= String is text, that Is, a “string of characters”10 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Some observations about this page number assignment:
= You address the property of an object by naming both the object and
the property, joined by a period: object-name.property-name.
© The equal sign in the line of code above is an assignment command; it
sets the value of something. In our case, it sets the current document's
page number to 6.
= JavaScript is case-sensitive. Upper- and lowercases are distinct; our pro-
gram would have failed if we had typed This. PageNum.
= Counterintuitively, Acrobat internally numbers pages in a document
starting at zero; the seven pages in our Acrobat file are numbered zero
through six. Thus, when our JavaScript set the pageNum property to 6, it
‘was moving us to the last page in the document.
Object methods
A method is a command that is associated with a JavaScript object. Just as a
dog can be given commands (“Sit “Heel,” “Spit that out this instant!”),
JavaScript objects have commands that they can carry out. The set of com-
mands is different for each type of object. For example, Table 1.2 lists some
of the commands the app object knows how to execute.
Table 1.2 App Object Methods (Partial)
beep Play the system's “beep” sound
alert String Put up an alert dialog box with the specified text
goBack Go to the previous view
‘goForward Go to the next view
newDoc ‘Open a new, blank Acrobat file
‘openDoc String ‘Open an Acrobat file. The string argument contains
the name of the file
In our Order Form JavaScript, we executed the app object's beep method:
app. beep
Note that we execute an object’s method in the same way that we refer to
one of its properties: the object name, a “dot,” and the method name.1 | WELCOME TO JAVASCRIPT! 14.
‘Some methods need additional information in order to carry out their task;
for example, the openDoc method listed in Table 1.2 needs to know the name
of the file you want to open. Information handed to a method is called an
argumentto that method. The openDoc method takes a filename as its.
argument; this information, surrounded by parentheses, must follow the
method name. An invocation of openDoc would look something like this:
‘app-openDoc("TermPaper.pdf")
‘The above JavaScript statement would open an Acrobat file named
‘TermPaper.pdf.
Sometimes when you give a dog a command, you expect the dog to give you
something back: the command, “Fetch the stick, boy!” should yield a stick in
your hand, Similarly, many JavaScript methods have a return valug some
piece of data they give back to the JavaScript program. The openDoc method
we invoked above actually returns a Doc object representing the newly
opened document, though our single-line use of openDoc just ignores it. We
shall look at return values in much more detail in the next chapter.
JavaScript Program Syntax
Here we must discuss a couple of short topics regarding how JavaScript
commands are put together into a program.
JavaScript statements
A JavaScript program—any computer program—consists of a series of
statements, each of which carries out one step in the overall task. Our sam-
ple program consists of two statements:
this.pageNum = 6
app.beep
Usually, each line within a JavaScript program will contain a single JavaScript
statement, as in our program above. You can put more than one statement
on a line, separated by semicolons. Our two-line program could have been
written on a single line:
this.pageNum = 6; app.beep
Why would you do this? Purely for esthetics; some people just prefer to
combine very simple statements together. I recommend against this practice;12 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
most programs are much easier to read if you have only one statement
per line.
If you read other people's JavaScripts, you may notice that many program-
mers put semicolons at the end of every line in their program:
this.pageNum = 6;
app. beep;
This doesn't hurt anything, but it’s quite unnecessary. Most of them do it
out of habit; JavaScript looks very much like the programming languages C
and C++, both of which require that all statements end with a semicolon.
‘You can leave out the semicolons.
JavaScript text
JavaScript programs are simply text files; you can write them with any text
editor or word processor and then copy and paste them into the Acrobat
JavaScript Edit dialog box. In fact, the Windows version of Acrobat lets you
specify an external editor that should be used for editing your JavaScripts;
‘welll discuss how to do this at the end of the chapter.
Space and tab characters within a JavaScript line have no particular mean-
ing in JavaScript. You can use them as you wish to format your program.
This is a purely visual issue; you want to format your JavaScript code so that
it's easy to read.
Use whitespace characters lavishly! Reading program code is tedious at best;
a program can be nearly undecipherable if the programmer has not format-
ted the code for easy reading. This is an important enough issue that I shall
be providing formatting tips for many of the JavaScript constructs we use in
this book.
JavaScript Errors
In the (ahem) rare event that you have an error in your JavaScript—you mis-
spelled a variable name, miscapied a piece of code, and so on—Acrobat will
present you with a dialog box called the JavaScript Console (Figure 1.7). The
Console will display a message indicating the nature of the error; it will
sometimes (but not always, alas) also indicate the line number within the
script in which the error took place.4 | WELCOME To JAVASCRIPT! 43.
Figure 1.7. The JavaScript
Console is a dialog box used by
Acrobat to display error mes-
‘sages that indicate a problem
in your JavaScript code.
Error messages can be somewhat cryptic at first, but with time and familiar-
ity they become useful. The most common messages you are likely to see are
the following:
= Reference Error: - XXX is not defined
This indicates that you misspelled something; the name “XXX” (or
whatever) is not one that JavaScript knows. Remember that JavaScript
is case-sensitive; there is a difference between app (which JavaScript
knows) and App (which it doesn't know),
= Syntax Error
This means that JavaScript could not make sense of something in the
code. This usually means you left something (a comma, a number, a close
parenthesis) out of your script. An example of a syntax error would be
app.alert(*Hi, Mom", 3
This line is missing its closing parenthesis.
The set of possible error messages is quite large, though most are pretty
hard to provoke. Just sit tight, read the message, and carefully examine the
suspect JavaScript code for misspellings and omissions.
JavaScript Comments
JavaScript code can be pretty cryptic. Puzzling over someone else's code (or even
your own code from six months ago), trying to figure out exactly what it’s doing,
can be tedious. As a courtesy to others looking at your code and as an aid to
your future self, itis very important to place comments in your JavaScript code,
A JavaScript comment is text in your code that is ignored by the JavaScript
“machine.” The purpose is to let you place your own notes in the text to be
read by human beings examining the code.414 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
JavaScript recognizes (that is, ignores) two kinds of comments:
= Single-line comments start with a double slash (//) and extend to the end
of the line in the JavaScript code. These are intended for brief comments.
[/This is a single-line comment.
= Block comments start with a /* and end with a */. Between these two
delimiters can be as much text as you wish, spread out over as many
lines as you wish within the JavaScript file. This is for longer comments.
/* Here we have a block comment. This
text will be completely ignored untiT
we end the comment, right here. */
An example
Consider the following, uncommented JavaScript from later in this book:
var txtField = event.target
txtField.fillColor = color. red
txtField.textColor = color.white
Since we have not yet discussed these commands, the purpose of this script
and how it carries out that purpose are very unclear.
(On the other hand, if we include comments in the code, then it becomes
possible for someone unfamiliar with the program to at least know what the
intent of the program is and generally what it's doing:
/* This program changes the background and text color of
a text field when the user tabs into or clicks in the
field. */
var txtField = event.target // Get a reference to the text field
txtField.fillColor = color.red // Set the background to red
txtField.textColor = color.white // Set the text color to white
‘This version of the program is much clearer, even to someone new to the code.
Comments are a Force for Good in programming. Any script more complex
than a couple of lines should include comments that describe what it does
and how it works.
All of the examples in the rest of this book will be heavily commented to
make them as comprehensible as possible.2 | WELCOME TO JAVASCRIPT! 28,
Acrobat JavaScript Guide
This book is a nonprogrammer's introduction to using JavaScript within
Adobe Acrobat. The full description of all of the things you can do with
JavaScript in Acrobat is presented in a document distributed with the full
Acrobat package: the Acrobat JavaScript Object Specification (AJOS) (Figure
1.8). This is the technical specification of all of the object types available to
your JavaScript programs ‘Actobat.
‘The AJOS is a technical specification, not a document you would read from
one end to the other. It gives a detailed description of every JavaScript
‘object type available in Acrobat and the properties and methods of each.
Where the book you are reading presents a series of examples of how to
carry out specific tasks in JavaScript, the AJOS describes everything you can
do in Acrobat with JavaScript.
Tea Ho 86
Acrobat JavaScript Object se Aevobat
te Figure 1.8 The Acrol
Specification ace
‘Specification describes,
in detail, all the objects
available to an Acrobat
fe] JavaScript, their proper-
P| ties, and their methoas.
To give you a bit of the flavor of the AJOS, Figure 1.9 shows a screenshot of
the complete description of the app object’s beep method.U6 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
beer
Perenaters [nType)
Ratna. None
“This mettod cones the ayrem plays sotnd. The werner sound wn the valoe ed am a
Slow
ed
Ener e
co 7
on 2
Demtioecenns 1+
‘Mowe: On Apple Macintosh end UNIT stems tha ap pes nored
Figure 1.9 The description of the app object's beep method is a
‘good example of the type of description provided for every object,
‘method, and property in the Acrobat JavaScript Object Specification.
I shall be making occasional references to the AJOS throughout this book.
You can open the AJOS directly from Acrobat by selecting Help > Acrobat
JavaScript Guide,
Using Your Own Text Editor
The text editor built into Acrobat’ JavaScript Edit dialog box (see Figure 1.6)
is pretty minimal, It lets you type in your JavaScript, but it has no particularly
fancy editing capabilities. For short JavaScripts, this is not important; when
typing long, complex JavaScripts, however, you will miss having a fully fea-
tured text editor.
On the Macintosh, you can type your JavaScript into your own text editor
and then copy and paste it into the JavaScript Edit dialog box. For what it's
worth, my favorite free text editor on the Mac is BBEdit Lite, by Bare Bones
Software (www.barebones.com).
‘The Windows version of Acrobat can automatically launch the text editor of
your choice when you click on the Edit button in the Add an Action dialog
box (see Figure 1.5). To set this up, you must specify in Acrobats Preferences
the editor you wish to use for editing JavaScripts.4 | WELCOME TO JAVASCRIPTI 47
To specify a text editor to use when editing JavaScripts:
Start with Acrobat open.
2. Select File > Preferences > General.
Acrobat will present you with its Preferences dialog box.
+2. Select JavaScript in the list of Preferences categories.
‘The Preferences dialog box will display the controls that affect Acrobat’s
JavaScript support (Figure 1.10).
Figure 1.10 The Acrobat Preferences dialog box allows you
10 use your favorite text editor to enter your JavaScript code.
Alas, this is available only in the Windows version of Acrobat.
*
Among the JavaScript Editor controls, select External Editor.
4, Click the Choose button and then navigate to the .exe file for the editor
you want to use when editing JavaScripts.
8. Click the OK button.
‘That's all there is to it. Now, when you go to edit a JavaScript, Acrobat will
automatically launch your text editor. Type your JavaScript code into the
text editor's window, save the text, and then close the text editor. Your
JavaScript will be automatically entered into Acrobat.
Among Windows text editors, I'm rather fond of TextPad (www.textpad.com)
and UltraEdit (wwwcultraedit.com); they are both relatively inexpensive
shareware and well worth the money.18Page and Document
JavaScripts
There are four broad types of JavaScripts in Acrobat, each differing in where
it’s used in the Acrobat document.
Form Field JavaScripts are attached to form fields. As we saw in the pre-
vious chapter, Form Field scripts are associated with events that occur
with a form field: Mouse Down, On Focus, and so on.
Document JavaScripts are associated with the opening of the Acrobat
file, Acrobat executes these when the document is first opened.
Document Action JavaScripts are executed when one of a set of prede-
fined events happens with the Acrobat file: the file closes, is saved, and
soon.
Page JavaScripts are associated with a particular page. You can provide
scripts that Acrobat will execute when the user enters that page, leaves
that page, or both.
We discussed Form Field JavaScripts in Chapter 1. In this chapter, we'll look
at how to write the other three types of scripts,20 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Project
(Files: Ch02_Example.pdf, Ch02_Example_raw.pdf)
‘Our sample file for this chapter is the pet store catalog pictured in Figure 2.1.
In the course of our discussion, we'll add examples of Document, Document
Action, and Page JavaScripts to this file.
ae
ja Pe ey
Fass “Catalog
Thnk of the fin youl te he withae a>
tha Une bby. They bk gato he Fo ae
nd mary ot Bem cn be fay peck Wn
or en be rps!
Figure 2.1. We will add
several JavaScripts to
Document JavaScripts
Document JavaScripts are attached to an Acrobat document and are exe-
cuted by Acrobat upon opening that document. This is @ convenient way to
present the reader with an initial “splash screen” or to carry out some other
start-up activity when the user opens your PDF file. You may attach as
many Document JavaScripts to an Acrobat file as you wish.
As an example, we'll add a Document JavaScript to our catalog that displays
a greeting when the reader opens our catalog document (Figure 2.2).
‘Welcome tothe 1-OMTPets catalog.
Figure 2.2. We'll use a Document JavaScript to
present this welcoming dialog box when our user
‘opens the Acrobat file.2| PAGE AND DOCUMENT JAVASCRIPTS 24.
To attach a Document JavaScript to an Acrobat document:
Start with the document open in Acrobat.
4, Select Tools > JavaScript > Document JavaScripts (Figure 2.3).
Figure 2.3. The first step
in creating a Document
JavaScript is to select
Tools > JavaScript >
Document JavaScripts.
Acrobat will display the JavaScript Functions dialog box (Figure 2.4).
Figure 2.4 The JavaScript
Functions dialog box is where
you add, edit, and delete
Document JavaScripts.
2. Type a name in the Script Name field of the JavaScript Functions dialog box.
Each Document JavaScript must have a name. Make it descriptive and
short, and avoid using any tabs or spaces. In our case, le’s use the name
‘Welcome, since that’s the purpose of this script.
3. Click the Add button,
Acrobat will present you with the JavaScript Edit dialog box
(Figure 2.5). Note that this dialog box appears with some JavaScript
code already entered into the text field. This code is the starting
point for a JavaScript function definition; since we're not going to
be defining a function, you can delete this initial code.22 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Figure 2.5 Acrobat uses this same JavaScript
Eait dialog box whenever it wants you to type
some JavaScript code. In the case of Document
JavaScripts, Acrobat supplies some initial JavaScript
code, which we won't use; you should delete it.
4. Type your own JavaScript in the Edit box. In our case, the JavaScript
should be a single line:
app.alert("Welcome to the 1-Off Pets catalog!", 3)
This JavaScript displays the alert shown in Figure 2.2. The app object’ alert
method displays an alert with the specified text. The 3 indicates the kind of
icon that should appear in the alert. We'lllook at this method in more detail
in Chapter 13, (You may recall we discussed the app object in Chapter 1.)
8. Click the OK button to return to the JavaScript Functions dialog box
(Figure 2.6), which now lists our new Welcome script.
@. Click Close to return to the Acrobat file.
7. Try it out by saving the Acrobat file, closing it, and then reopening it.
Acrobat should display the alert shown in Figure 2.2,
Figure 2.6 The Welcome
JavaScript now appears in the
list of Document JavaScripts
attached to this Acrobat file.2 | PAGE AND DOCUMENT JAVASCRIPTS 23
Global Variables
One unobvious characteristic of Document JavaScripts is that any variables
they create are visible to all the other JavaScripts in your document. For
example, imagine you created a Document JavaScript with this line in its
var iconType = 3
Here, we've created a variable named iconType whose value is 3, All the other
scripts in our Acrobat document, of any sort (Document, Document Action,
Page, Form Field) can use the variable iconType instead of the number 3.
app-alert(*Welcome to the 1-0ff Pets catalog!", iconType)
This can be very convenient. If you have, say, 50 scripts in your document that,
create alerts like the one above, changing the definition of iconType in your doc-
‘ument script will change the icon displayed by all 50 of those alert JavaScripts.
Our icontype variable is referred to as.a global variable; itis accessible by
all scripts throughout the Acrobat document. We will be making use of
global variables occasionally in this book's JavaScripts.
Document Action JavaScripts
‘A Document Action JavaScript is executed when a specific event occurs with
the document. There are five events to which you can attach a JavaScript:
= Document Will Close means Acrobat is about to close the document.
= Document Will Save means Acrobat is about to save the document.
= Document Did Save means Acrobat has finished saving the document.
= Document Will Print means Acrobat is about to print the document.
= Document Did Print means Acrobat has finished printing the document.
‘To see how to attach a JavaScript to one of these events, let's make another
change to our catalog. When the user closes the Acrobat file, le’s thank the
user for looking at our wares, as in Figure 2.7. We'll do this by attaching a
to the Document Will Close event,
Figure 2.7 We'll use a Document Will Close JavaScript
to present a farewell message to our user.24 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
‘To attach a Document Action JavaScript to a document:
4. Start with the document open in Acrobat. Select Tools > JavaScript >
Set Document Actions (Figure 2.8).
Figure 2.8 Selecting
Tools > JavaScript > Set
Document Actions takes
you to the Document
Actions dialog box
Acrobat will display the Document Actions dialog box (Figure 2.9).
2, Select Document Will Close, and click the Edit button.
Acrobat will display the JavaScript Edit dialog box.
Decument Will ave
Decarment tn Save
Decament wil Print
Decarment Ox Print
Figure 2.9 The Document
Actions dialog box lets you
attach a JavaScript to any
one of five different events.
3. Type your JavaScript in the dialog box. For our purposes, the script
should be:
app-alert ("Thanks for looking at our catalog!", 3)2 | PAGE AND DOCUMENT JAVASCRIPTS 28
4. Click OK to back out of the JavaScript Edit and JavaScript Functions
dialog boxes; you will now be back at your Acrobat page.
5. Tryit out: Save the Acrobat document and then close it. Acrobat will
present you with the Thanks alert, as shown in Figure 2.7.
Page Action JavaScripts
A Page Action is an Acrobat action that's associated with the opening or
closing of a particular page. These can be any of the Action types that
Acrobat knows: such as menu items, movie actions, sound actions—and
in our case, of course, JavaScript actions. We'll attach a JavaScript action
to our page.
‘There are two kinds of Page Actions in Acrobat:
= Page Open actions are executed when the user scrolls to the page
(a Page Open event).
= Page Close actions are executed when the user leaves the page (a Page
Close event).
Asan example, we'll attach a Page Open action to the third page in our cat-
alog to announce that 1-Off Pets is having a sale on pet croquet balls. Our
Page Open action will display the alert shown in Figure 2.10 when the user
‘opens page 3.
Figure 2.10 We shail use a Page Open action attached to
page 3 of our catalog to announce a sale on croquet balls.
To attach a Page Action to a page in an Acrobat Document:
Start with the document open to the proper page; in our case, this is page 3.
4, Select Document > Set Page Action.26 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Acrobat will display the Page Actions dialog box (Figure 2.11).
2. Select the Page Open event and click the Add button.
Acrobat will present you with the Add an Action dialog box that we saw
in the previous chapter (Figure 2.12).
oe te ppm ete tame ge:
Opes) ware ma
Figure 2.11. The
Page Actions dialog
box allows us to
associate an action
with each of two
events: Page Open
and Page Close.
Figure 2.12 The
‘Add an Action dialog
box allows us to
specify the details of
the action associated
with an event, Here,
we are associating a
JavaScript action with
the Page Open event.
3. Select JavaScript for the action type and click the Edit button.
Acrobat will display the usual JavaScript Edit dialog box.
4. Type your JavaScript into the dialog box. In this case, use the following:
app.alert("Special on Croquet Balls this week only!
= Call now", 3)
5. Click Set Action and OK to back out of all the dialog boxes until you
are again looking at the Acrobat file page.
6. Try it out by going to the previous page in the Catalog and then return-
ing to page 3; you will see the alert that’s pictured in Figure 2.10.Form Field Highlighting
A recurring theme throughout this book is the importance of user feedback
in forms. It should be clear to a user at every moment exactly what he or
she is expected to do and what part of your form is expecting information.
In this chapter, we shall look at one useful way of doing this; we shall create
a form whose text fields exhibit colored entry highlighting—that is, they
change color when the user clicks on them or tabs into them.28 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Project
(Files: Ch3_Start.pdf, Ch3_End.pdf)
We shall add colored entry highlighting to the order form in Figure 3.1.
This Acrobat file starts out as an entirely unremarkable form a user would
fill out to order a copy of his or her records. As you can see from Figure 3.2,
this form contains a handful of text fields and a single Submit button.
3
5
3
na
Figure 3.1. We shail add entry highlighting to this form.
— ——— = ———J
Address
a — |
Reason for
Request
Figure 3.2 Our form contains four text fields for collecting data from
‘the user and a single button that submits data to the company.3 | FORM FIELD HIGHLIGHTING 29
Because of the colored entry highlighting, when the user clicks in a text
field, the field will turn red, indicating that it’s the active field (Figure 3.3).
Narre Figure 3.3. When the user clicks
N in a text field, the field's contents
are
will be highlighted, displaying white
text against a red background.
The JavaScript
Normally, text fields contain black text displayed against a white or trans-
parent background. We are going to modify the text fields so that when the
user clicks on a field (or tabs into it), the field turns into white text against a
red background, indicating that the field is ready to receive keyboard input
(see Figure 3.3).
Approaching the Problem
To implement entry highlighting, we shall attach JavaScripts to the On
Focus and On Blur events for each text field in our form (Figure 3.4). On
Focus events occur whenever a form field becomes the target for data entry,
usually because the user clicked on the field or tabbed into it. On Blur
events occur when a form field loses the focus—that is, when some other
form field becomes the target for data entry. (If the name On Blur seems a
bit peculiar for this event, what single word would you use to describe the
opposite of focus?)
Figure 3.4 We shai
‘add two scripts to each
text field in our form:
an On Focus script that
adds highlighting and
an On Blur script that
removes it again.30 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Our On Focus JavaScript will set the form field’s background color to
red and turn the text color to white, The On Blur script will set the back-
ground and text colors back to transparent and black, respectively. We will
need to add these JavaScripts to all of the text fields in which the user may
enter data.
By the way, the On Focus and On Blur events were added in Acrobat 5, so
our highlighting won't work if the form is viewed with earlier versions of
Acrobat. (Nothing will break if the form is viewed with Acrobat 4; the user
just wor't see the highlighting.)
The Code
Step 1: The On Focus JavaScript
‘The following JavaScript is intended for the On Focus event of each of the
text fields in this form (see Figure 3.2)
Breferenceto] // This is the On Focus JavaScript
—— var txtField = event.target
the color | | txtField.fillColor = color.red
Le = color.white
The code in detail:
var txtField = event.target
This first line gets the field that caused the On Focus event to occur (the
target of the event) and assigns it to a named reference (a variable) whose
name is txtField. This is the name by which we will refer to our text field
in the remainder of the JavaScript.
txtField.fillColor = color.red
txtField.textColor = color.white
Having gotten a reference to our text field, we set two of its properties:
m= fillColor is the background color of the form field. We set it to red.
m= textColor is the color of the text in the form field. We set it to white.3 | FORM FIELD HIGHLIGHTING
Notice that we specify our colors as color.red and color.white. Acrobat
provides a set of predefined names for common colors, as follows:
= color.transparent = colorwhite
= colorgreen = colorcyan
= coloryellow = colorgray
= colorblack = colorred
= colorblue = colormagenta
= colordkGray = colortGray
Step 2: The On Blur JavaScript
Our On Blur script is identical to the On Focus script—only different. We
set the textColor and fil1Color properties back to their original values:
var txtField = event. target
txtField.fllColor = color. transparent
txtField.textColor = color.black
‘Similarly to step 1, we get a reference to the text field that caused the On
Blur event and then change the colors of the background (transparent) and
text (black). color. transparent is a valid color in this context.
That's all you need to do. Once you add both of these JavaScripts to each
text field in your form, your form will have colored entry highlighting and
your users will be very impressed.
Customization Notes
‘There is nothing too difficult about customizing this JavaScript to your own.
purposes; in fact, the JavaScripts we use here can be used, unmodified, for
any text field in any form.
The only sensible bit of customization you may want to do is select other col-
rs for your text fields. You can highlight your text field with any combination
of fl 1Color and textColor you wish. The list at the end of step 1 shows the82 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
standard, named colors that Acrobat recognizes; you can, however, set the col-
ors to any RGB, CMYK, or gray values you wish, using a format such as this:
txtField.fillColor = ["RGB", .5, 1, .5]
The values for the color components—R, G, and B, in our case—must each
be a number between 0 and 1.
Finally, if you set both a field’s il Color and textColor to color. transparent,
the field effectively disappears. You could use this to dynamically hide a form
field; however, welll look at another, better way to do this in Chapter 8.Checking
Acrobat Version
Prior to Acrobat 4, support for forms in Acrobat was practically nonexistent.
Acrobat 4 introduced robust support for forms into Acrobat, and Acrobat 5
enriched the capabilities of the form mechanism still further. Unfortunately,
as a form designer, you have no control over what version of the Acrobat
viewer your user may have, and this ercates a challenge in form design.
Inevitably, you must make an assumption as to what version of Acrobat is
being used to view your form. If a user has version of Acrobat earlier than
this, you must detect the fact and handle the situation gracefully.
This is what we shall discuss in this chapter. We shall see how to determine
the version of Acrobat our user has and how to automatically close the doc-
ument if the user's program is too primitive to present it properly.‘84 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Project
(Giles: ChO4_Examplel.pdf, Ch04_Example1_Raw.pdf)
Figure 4.1 shows a form that uses colored entry highlighting to change a
form field’s color when the user selects it. (Chapter 3 shows you how to
do this, by the way.) This form implements the highlighting by attaching
JavaScripts to the On Focus and On Blur events for each text field. Because
these two events were added in Acrobat 5, our form will not work properly
with versions of Acrobat earlier than 5.
ing
Nace
Figure 4.1 This form depends on form field events that were
added in Acrobat 5. We shall add a Document JavaScript that
checks the current user's Acrobat version and present an
alert if the version isn’t sufficiently recent.
In this chapter, we shall further modify this form, looking at the user’s
Acrobat version number. If the version number is less than 5, we shall first
put up an alert (Figure 4.2) announcing the fact and then close the form.
Qtr storie teem
G5
Figure 4.2 We shall display this alert if the users
version of Reader is not recent enough.4 | CHECKING ACROBAT VERSION 35
The JavaScript
Checking for the proper version of Acrobat is something you would want to
do when the user first opens the document. For this reason, we shall use a
Document JavaScript, which Acrobat will execute when the user first opens
the document.
Approaching the Problem
This script is relatively simple. We shall look at the user's Acrobat version
and compare it to the minimum version of Acrobat we need (Acrobat 5, in
our case). If the version is less than 5, we'll post the alert shown in Figure 4.2
and then close the Acrobat file. We can easily determine the version number
by examining the app object’s viewerVers ion property, whose value is the
version number of the current Acrobat viewer.
The Code
This JavaScript needs to be entered as a Document JavaScript. (Refer to
Chapter 2 for a reminder of how to attach a Document JavaScript a docu-
ment.) Remember that Document JavaScripts must always have a name,
T'm going to name our script CheckVersion (Figure 4.3)—descriptive, if
[etre vewerver] unimaginative.
ion less than 5? Vi (app.viewerVersion <5) {
Display an alert app.alert("You must have Acrobat Reader 5.0 or later to use
(oath this text = this form.*)
this.closeDoc(true)
}
The code in detail
This program is built around a call to the JavaScript if command. This
‘command compares two things (in our case, the Acrobat version and the
number 5) and executes a block of code if the comparison is true. The if
command and its cohort, e1se, are ubiquitous in JavaScript; we shall be see-
ing them quite a lot throughout this book. Anytime your JavaScript needs38 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Figure 4.3 Every Document
JavaScript must have a name.
We shall call ours CheckVersion.
This is apt, if not exactly catchy.
to do one thing in some circumstances and something else otherwise, these
are the programming tools you use.
if (app.viewerVersion < 5)
Here is where we look to see if our Acrobat version is less than 5; change
the numeral to reflect your minimum required version of Acrobat. (We are
examining the viewer¥ersion property of the app object.) Most professional
forms should make sure the user has at least Acrobat 4.
‘The JavaScript code that should be executed if the comparison is true (in
other words, if the version of the viewer is less than 5) appears between the
braces that immediately follow the comparison. In our case, there are two
lines within this “conditional blocl
app.alert("You must have Acrobat Reader 5.0 or later to use this
= form.")
Here is where we tell the app object to display an alert, as in Figure 4.2. The
text in the parentheses is the text that should appear in the alert; you can
change this to anything you wish,
this.closeDoc(true)
Finally, having informed the user of the problem, we tell the current docu-
ment to close itself. Remember that "this" refers to the current document
(that is, “this document”). The Boolean true indicates that the user should
not be given a chance to save the document before it closes. If you change
the Boolean to false, Acrobat will present the user with a standard “Do you
want to save first” dialog box (Figure 4.4). This would allow the user to save
the Acrobat file before it was closed. (For example, you might want to use4 | CHECKING ACROBAT VERSION 37
false if you are using the closeDoc method in a Close Form button you put
in your form; it would give the user the opportunity to save whatever
changes he or she has made to the form.)
Figure 4.4 If you supply a false to the closeDoc
method, Acrobat will give the user a chance to
save the Acrobat file before closing it. This can be
useful, preventing the user from accidentally
osing form field entries.
Asa convenience, you may leave out the Boolean value if you do want a
“save” dialog box; in this case, your call to closedoc would look like this:
this.closeDoc()
This saves you from having to type “false’ but is otherwise no different
Testing the Code
‘Testing this program—to make sure you haven't mistyped something, for
‘example—is a bit tricky if you're using Acrobat 5 to create your form. Since
‘our comparison (app.versionNumber < 5) never comes up false (our own
version of Acrobat is never less than 5), our calls to app.alert and
this. closeDoc will never be executed: if you have misspelled one of these,
you won't know it until you (or a user!) try to open the document with an
earlier version of Acrobat.
‘One way you can test this script is to temporarily modify it by placing true
in the 1f operator’s comparison clause:
If (true)
app.alert("You must have Acrobat Reader 5.0 or later to use
= this forn.")
this.closeDoc(true)
}
This forces the code in braces to be executed, letting you see if there are any
errors hidden in there.38 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Customization Notes
‘The obvious opportunities for customization are:
= Change the version number in the ‘f line to whatever minimum
Acrobat version you want. Again, most forms should at minimum
check that the version is 4 or greater.
= Change the text in the alert to whatever you wish to have appear on
screen.
Following are some less-obvious changes you can make to this program.
Testing for Viewer Type
Finally, you can easily modify this chapter's JavaScript code to see which
Acrobat program your user is using to look at your form: Acrobat Reader or
the full Acrobat. The app object has a property named viewerType that will
have one of two string values, "Reader* or “Exchange*, depending on which
type of viewing software the user has. If your form needs the capabilities of,
the full Acrobat package (perhaps your form lets the user save the form data
to disk, something only available in the full Acrobat), you could modify this
chapter’s Document JavaScript to read as follows:
-=="means &
[equal to”
Lif (app.viewerType == "Reader") (
app.alert("You must have the full Acrobat to use this forn.*)
this.closeDoc(true)
}
‘This will warn the user and then close the document if he or she looks at
your form with the Acrobat Reader.
Alert icons
The alert that we are displaying in this chapter's program displays a Halt
icon, indicating that something has gone so wrong that we're going to stop
what we're doing.
Sometimes, however, you don't want quite so emphatic an icon in your
alert. The app. alert method allows you to specify, in addition to the text
that should go into your alert, the icon that should appear. See Chapter 13
for a full discussion of how to specify the icon used in your alerts.Calculating
Form Fields
Calculation is fundamental to so much of what we do in the computer
world. Spreadsheets, statistical analysis, accounting information—even
unobvious things like word processing and page layout—all depend on a
computer's ability to perform calculations, saving delicate little human
brains for more lofty pursuits. Because it runs on a computer, Acrobat can
also calculate, allowing you to specify that a form field’s value should be
calculated, rather than typed in by the user. You do this using either a
JavaScript or one of Acrobat’s predefined calculations; here we shall learn
how to create calculated form fields that use both methods.40 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Project
(Files: ChO5_Example_2.pdf, Ch05_Example_2_Raw.pdf)
In this chapter, we shall add calculations to the purchase order form in
Figure 5.1. This form is used by employees of a small business to order
office supplies or other necessary items. For each item users want to buy,
they supply a description and the price and quantity they need. The form
automatically fills in the subtotal, tax, and total purchase price.
Figure 5.1 In this chapter, we shall add a series of calculations to
the fields in this form so that the fields for item cost, subtotal, tax,
and total cost are automatically filled in.
Looking at Figure 5.2, we can see that the form is made up of text fields
arranged in six columns for the item name, price, quantity, subtotal, tax
amount, and final cost of that item. We also have a final total amount at
the bottom of the form. If this were a form you made for your company,
it would also need a Submit button and, perhaps, a Clear Form button; 1
‘omitted those here for the sake of compactness.
Figure 5.2 Here are the form fields in our sample form. We
shall turn the fields in the txtSubtotal, txtTaxAmt, and txtCost
columns and the txtTotal field into calculated fields.5 | CALCULATING FORM FIELDS 4%.
The calculations we need to put into this form are as follows:
For each purchased item:
Subtotal = price x quantity
= Tax = tax rate x subtotal
@ Item cost = subtotal + tax
Finally,
® Total = sum of the item costs
Let's see how to add these calculations to our form.
The JavaScript
Creating a Calculated Field
You may remember that a text field can be declared to be a calculated field.
Acrobat will automatically recalculate the value of this field as needed: all
we need to do is tell Acrobat exactly what calculation to perform. We do this,
from the Field Properties dialog box (Figure 5.3).
Figure 5.3 You add a calculated value to a form
field in the Field Properties dialog! box's Calculate panel.42. EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Numeric Calculations with a Text Field?
‘The value of a text field is the text that fleld contains. If that text is a valid number, then
the field's value can be used in a JavaScript calculation, as we are doing here. If a text
field's value Is not a valid number (If the field contained “Mooseberries”, for example),
then the value may still be used in a calculation, but the value will be interpreted as 0.
‘The easiest way to ensure that a text fleld contains only valid numbers is to set Its format,
to Number; Acrobat will then reject any keystrokes that are not part of a numeric value.
(You also need to do this if you want to use the Acrobat predefined calculations.)
To set a text fleld’s format to Number:
Start with the text feld selected with the Acrobat Form tool.
1
2
3
a
5.
This form field will now accept only numbers, a decimal point, and an initial plus or
minus sign.
Double-click on the text field to gain access to its properties.
Go to the Format panel (Figure 5.4).
Select Number from the list of avallable formats.
Select other options (currency symbol, and so on) if they seem useful.
Click the OK button.
Orrmernmint (Oalar
eemtettcominn (125456)
ere: |
Como
Ours
Sa asa
Sw 2500
a i
Soecat
|
|
(a)
Figure 5.4 To ensure that a text field contains only
2 valid numeric value, set its format to Number.5 | CALCULATING FORM FIELDS
‘To attach a calculation to a text field:
4. Double-click the text field.
You will now be looking at the Field Properties dialog box for that text
field.
2. Click the Calculate tab.
You are now looking at the controls that let you specify a calculation
for the value of the text field.
3. Fora simple calculation, click the second radio button (“Value is
the...”) and select from the pop-up menu of predefined calculations. If
you don't see this second radio button, that means that the field’s for-
mat isn’t set to Number.
4. If you need a more complex calculation, click the third radio button
(“Custom calculation script") and then click the Edit button to enter a
JavaScript.
Predefined calculations
‘There are five calculations that are built in to Acrobat. Without writing a
speck of JavaScript, you can set the value of a text field to the sum, product,
average, minimum, or maximum of two or more other form fields. This is.
the meaning of the second radio button in the Field Properties dialog box’s,
Calculate panel.
Again, these predefined calculations are available only if you have explicitly
set the format of the text field to Number.
To use one of the predefined calculations:
Start in the Field Properties dialog box’s Calculate panel.
1. Select the radio button that “turns on” the predefined calculations
(Figure 5.5).
© vaive is we CEERI] ofthe flowing felis
eR
Figure 6.5 The second radio button lets you perform simple calculations
‘on two or more fields.44 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
2. From the pop-up menu (Figure 5.6), select the calculation you want.
‘Product (7)
average
minimum Figure 5.6 Acrobat lets you choose
ee ‘one of five predefined calculations.
3. Either type into the textfield the names of the text fields that supply
the data for the calculation.
or
To save typing, click the Pick button and choose from the resulting list
(Figure 5.7) the data fields the calculation should use.
S Selec als
Seca ine come 1b sd fe
ey A ema)
feeb? | Figure 6.7 Clicking the
ites Pick button presents you
irom with the Select a Field dialog
eursam 2 box, which lets you choose
caro F the form fields whose values
Coe) should be used in a prede-
fined calculation.
It is far more convenient to select among the predefined calculations than to
write the equivalent JavaScript code. In our Purchase Order form, we shall
use the predefined calculations for the Cost field (whose value is the sum of
the subtotal and tax) and the Total field (the sum of all the items’ costs)
(Figure 5.8). The calculation of the tax requires multiplication by a con-
stant value (our tax rate), and so cannot be done using a predefined calcula-
tion. (Predefined calculations can multiply two or more form fields
together, but can't multiply a form field by a fixed number.) We shall write a
JavaScript for the Tax field
© Value is tne [sum (+) ofthe following elas:
‘eaSvbroral0, aaTaxAme O a)
Figure 5.8 The calculated value of our txtCost.0 field
will be the sum of the associated subtotal and tax amount.5 | CALCULATING FORM FIELDS 48
We could also use a predefined calculation for the Subtotal field (it's the
product of the price and quantity). Nonetheless, we shall do the subtotal
with a JavaScript; the reason for this will become clear when we see the
enhancements at the end of this chapter.
The Item Calculations
Let's add the calculations that apply to the individual purchase items in our
form. We need to apply calculated values to the fields txtTaxAmt, txtSubtotal,
and txtCost for each item. Note that the names we have applied to these
fields conform to the Adobe Hierarchical Naming Convention (see sidebar);
thus, as we go down the Tax column, for example, the names of the fields are
txtTaxAmt.0, txtTaxAmt 1, and so on. This naming convention makes the
field names easy to remember and can be useful when using a predefined
calculation, as we shall see when we discuss the txtTotal field.
In our discussion of the item-related calculations, we shall look at the
JavaScripts that apply to item 0, the first row of form fields. For the full
form, you will need to repeat these calculations for items 1, 2, and 3, chang-
ing the field names as appropriate.
Adobe Hierarchical Naming Convention
‘We have picked a consistent naming strategy for our text fields. The text fields associated
with the purchase items are named tttitem.0, txtitem.1, and so on. The fields that hold all
the other item-byitem information are named similarly (txtCost.0, txtCost.4; txtQty.0,
‘betQty.1; and so forth).
‘These names adhere to the Adobe Hierarchical Naming Convention. This is a set of loose
rules that specify how to assign names to related fields. These names are similar to the
URLs (Web addresses) that Identify Web sites. A “dot” Is used to separate different parts
of each name; related fields should share the first parts of their names to indicate their
relationship. Thus, txtCost1 and txtCost.2 are both text flelds that contain a cost.
This makes it easy to see the relationship among your text fields. Also, as we shall see
in calculating the Total field, the Hierarchical Naming Convention makes It possible to
refer to an entire set of form fields just by using the first part of their names. That is, in
a predefined calculation, “txtPrice” is a shorthand reference to all fields that start with
this name: txtPrice.0, txtPrice.1, and so on. See “Calculating txtTotal” below to see a
concrete example.46 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Calculating txtSubtotal.0
The subtotal for an item is the price per item multiplied by the number of
items you are buying. In terms of our form, this means that the value of
txtSubtotal.0 should be the product of txtPrice.0 times txtQty.0. This could
be done using an Acrobat predefined calculation, but we shall nonetheless
do this as a JavaScript. Two reasons:
= [want to make it clear that the predefined calculations are doing noth-
ing magical; anything the predefined calculations can do, you can easily.
do in JavaScript.
= Among the enhancements we discuss at the end of the chapter, we shall
see a good reason for doing all calculations as JavaScript. It has to do
with the appearance of fields in which the value is zero. But we'll come
back to this.
To attach this calculation to txtSubtotal.0, start by opening the Calculate
panel of the Field Properties dialog box (Figure 5.9). (Follow steps 1-2
under “To attach a calculation to a text field” on page 43 to reach this
panel.)
Click the “Custom calculation script” radio button and then click the
Edit button. Acrobat will present you with the JavaScript Edit dialog box
(Figure 5.10); type in the following JavaScript and click OK.
Name
Suber
‘Shor Description
(mmc ines isiom Nirmal iia evtewiaie
O Value isnot calculated
value s the [sum (4) —¥] ofthe following Reid
|
| © custom caleulation senpt
|
|
Figure 5.9 To calculate a form field's value using 3
JavaScript, you start by clicking the “Custom calculation
script’ radio button and then clicking the Eait button,5 | CALCULATING FORM FIELDS 47.
JavaScript Eat
Use this dialog 10 create and edit your JavaScript
[fa once = is geteararrce OT
far cn = ts pretty
Jeers wave = ance value * ative
Figure 5.10 You type your
Wns.Col2 calculation JavaScript into
(ew) Claret) (OK) _the standard JavaScript Eait
dialog box.
Remember that double-slashed lines indicate JavaScript comments, which
are ignored by Acrobat and JavaScript. You can omit these, if you wish,
although I recommend typing them in, as well. (They will help you remem-
ber what's happening when you return to the code later.)
// Get references to the price and quantity fields
[Get the form var price = this.getField("txtPrice.0")
les we need for
tine calculation | [Vat qty = this.getField("txtQty.0")
(/* Set the value of our text field to
the product of price and quantity.*/
‘event.value = price.value * qty.value
This short script is reasonably straightforward. We create variables price
and qty that hold references to the txtPrice and txtQty form fields. We then
multiply the values of those two fields and assign the resulting product to
something called event .value
The only unobvious part of this script is our use of the term event.value.
Ina calculation script, event refers to an Event object; this object contains a
variety of information associated with the calculation event that provoked
the execution of the script. In particular, event .value is a reference to the
value of the text field that is the target of the calculation. This is a conven-
ience; if we hadn't used the event object, we would have had to explicitly
obtain a reference to the txtSubtotal.0 field and used that in our calculation:
var subtotal = this.getField("txtSubtotal.0")
‘subtotal
jalue = price.value * gty.value
‘There's nothing wrong with this way of doing things; it just takes a
typing. (Minor laziness is a virtue in programming.)
more
At this point, we have calculated our subtotal, multiplying the price by the
‘quantity. Now, we are ready to calculate the tax amount.4B EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Calculating txtTaxAmt.0
‘The tax on an item is the subtotal for that item multiplied by your local
sales tax rate. In my area, the tax rate is 8 percent (those of you in states
without sales tax just keep quiet); so the amount of tax owed on each item
is the subtotal times .08,
‘As before, go to the Calculate panel for the txtTaxAmt.0 field (Figure 5.11).
Select the “Custom calculation script” radio button and click the Edit but-
ton. Type the following JavaScript into the JavaScript Edit dialog box:
var subtotal = this.getField("txtSubtotal.
event.value = .08 * subtotal.value
9 Costom ealclation erpt
Sabeota = this GetFiaba SUBIC OT
valve = 08 subtotal valve
Figure 5.11 The JavaScript for the txtTaxAmt.0 field
sets the field's value to the value of txtSubtotal.0
‘multiplied by the tax rate—in this case .08.
Here, too, our code is pretty easy: Get a reference to the txtSubtotal.0 field
and set event value to the subtotal’s value times .08.
There is an enhancement we can add to all of our txtTaxAmt fields, but Tl
defer that until later in the chapter (see “‘Global’ Tax Rate,” below).
Calculation Syntax
JavaScript calculations use the standard characters to denote basic arithmetic. You have
no doubt seen these characters in use throughout your computer experience: *
‘and */* correspond to addition, subtraction, multiplication, and division.
In addition, you can use parentheses to cause some parts of the calculation to happen
before others: The parts of your calculation that are in parentheses will be executed
before parts that are outside the parentheses. Thus, if you wanted to calculate the aver-
‘age of two varlables pricel and price?, you would express it this way:
var avg = (pricel + price2) / 2
We must first add the two prices together, then divide the sum by 2.5 | CALCULATING FORM FIELDS 48
Calculating txtCost.0
The final cost of each item in our Purchase Order form is the sum of that
item's subtotal and its tax. Because summation is one of Acrobat’s prede-
fined calculations, we shall use that mechanism, rather than a JavaScript, to
calculate the cost. (Don’t hesitate to not use a JavaScript if Acrobat provides
a convenient alternative; always use the simplest way to achieve your goal.)
As before, double-click the txtClick.0 field and go to the Calculate panel.
This time, specify a predefined calculation by doing the following:
1. Click the middle radio button (“Value is the
2. Select Sum in the pop-up menu.
3. Type into the text box the names txtSubtotal.0 and txtTaxAmt0.
Asan alternative, you can click the Pick button and choose those two
fields from the resulting list.
We have now calculated all of the information we need for item 0: its subto-
tal, tax, and cost. We have two more things to do: set up the same calcula-
tions for items 1 through 3 and then calculate the total cost of the order.
Calculating Items 1 through 3
‘The calculated fields for items 1, 2, and 3 are identical to those for item 0.
Repeat the same JavaScripts and predefined calculations but simply change
the number “.0” to“1/"2,” or “3,” to match the item number. (I always just
copy and paste the earlier script into my new field and then modify the item
numbers.)
Thus, the JavaScript for txtSubtotal.1 would be:
var price = this.getField("txtPrice.1")
var qty = this.getField("txtQty.1")
event.value = price.value * qty.value
Calculating txtTotal
Finally, we need to calculate the total amount of money owed—the sum
of all four items’ costs. This, too, is a summation; therefore, we can use
the predefined Sum calculation. Go to the Calculate panel for the txtTotal
field and, following the same procedure as for the txtCost fields, set theBO EXTENDING ACROBAT FORMS WITH JAVASCRIPT
calculated value for this field equal to the sum of the four txtCost fields, as
in Figure 5.12.
© Vaton i tre [sum (oS) of the flowing lds
‘BACost 0, BaCOsE ACOH, DCO We
Figure 5.12. The total cost of the purchase will be
the sum of the costs of the individual items. We can
use a predefined calculation for this.
Figure 5.12 shows all four txtCost field names typed into the calculation
text box. However, because the Cost fields have names that conform to the
Adobe Hierarchical Naming Convention, we can take a shortcut in specify-
ing the txtTotal calculation. If we enter the name txtCost into the calcula-
tion text box (Figure 5.13), Acrobat will take this as shorthand for all the
fields whose names start with txtCost-dot-something. This is a real benefit of
using the Hierarchical Naming Convention: You can refer to whole families
of fields by the initial part of their names. There’s no good reason not to use
this shortcut when the opportunity presents itself.
@ vatve is one [suis] ofthe following ea:
oicon a)
Figure 5.13 Because we used the Adobe Hierarchical
Naming Convention to name our txtCost form fields
(txtCost.0, txtCost.1, and so on), we can specify a
predefined calculation as being the sum of txtCost.
We're done! We now have a functioning order form that, given the price and
quantity, automaticaly fills out all the other information. Try it out. Type in
some numbers. Give the items imaginative and amusing names!
Calculation Order
‘The order in which our calculations take place in a form is important. We
must calculate the subtotal before we calculate the tax amount, the subtotal
and the tax amount before the item cost, and so on.
Sometimes you will find that the calculations in your Acrobat form seem to
bbe happening in the wrong order. You can specify the order in which your5 | CALCULATING FORM FIELOS 5%
form fields are calculated by selecting Tools > Forms > Set Field Calculation
Order (Figure 5.14).
.
>
.
Acessiy Checker.
Dae
es >
Page Templates.
Figure 5.14 To change the order in which your form fields
are calculated, select Tools > Forms > Set Field Calculation Order.
Acrobat will present you with the Calculated Fields dialog box (Figure
5.15), which contains a scrolling list of all the calculated form fields in the
current Acrobat file; the order in which the fields appear in this list is the
order in which they are calculated.
(Cleuiated Fels
‘The tist below specifies the order in which
Calculations willbe performed on indial Feds
seers.
faesbtorlt
fsbo?
asubtoal3 rr Figure 5.15 The Calculated Fields
peta dialog box lists all of the calculated
areca 3 (Pert) elds in your Acrobat file in the
cesta order in which they are calculated.
snaCost 2 4 You may change the position of the
fields in this list using the Up and
(Gare)
— Down buttons.
To change the position in the list of one of the form fields, simply select it
and click the Up or Down button as appropriate.
The fields should finally be in this list in calculation order. You must calcu-
late the subtotal before you can calculate the tax; you must calculate the tax
before you can calculate the cost of the item; and you must calculate the
cost of all the items before you can calculate the total cost. Therefore, in the2 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
list, Subtotal must be above Tax, which must be above Cost, which must be
above Total.
If you ever find your form is presenting blatantly incorrect results and you
can find nothing wrong with any of the individual field calculations, check
to make sure none of the fields are being calculated out of order.
Enhancements
‘There are a couple of enhancements we can add to our form. These are
strictly optional but will pay off in the long run. If you want to see them in
action, they have been applied to the file Ch05_Example1_B&W. pdf in the
chapter's samples. (BE-W, here, is short for Bells and Whistles.)
Hiding Zeros
In our form so far, there is one significant visual difference between the form
as we've been constructing it and the one pictured in Figure 5.1. In our ver-
sion of the form, all the calculated fields associated with “empty” rows have
zeros in them, the results of the calculations they perform (Figure 5.16).
Although this is technically correct, itis esthetically annoying. If we haven't
specified an item to be purchased, its associated form fields would be better
left blank, rather than displaying explicit zeros.
To eliminate this visual clutter, we need to change the calculation associated
with the txtSubtotal and txtTaxAmt fields. They should perform their calcu-
lations only if the corresponding txtQty has a nonzero value; if txtQty has a
zero value (which will be the case if that field is blank), then our subtotal
and tax fields should be blank—that is, they should have values of **
em Pree w Te cow
Fated ebro wel fee | tone
um | aoe
tal na
You (ne)
Figure 5.16 Unless we do something special, our calculated fields
will all show unsightly 0 values when there is no item purchased
in a particular row. It would look better if these were blank.
Here is the new calculation JavaScript for txtSubtotal.0:5 | CALCULATING FORM FIELDS 53.
// Get the two fields we'll need
J/ for our calculation
var price = this.getField("txtPrice.0")
var qty = this.getField(*txtqty.0")
Hit (aty.value ) // \= means “not equal to*
fevent.value = price.value * qty.value
Helse
fevent.value = **
Remember how the JavaScript if.e1se commands work: The if command is
followed by a comparison in parentheses; in our case, we compare qty.value
and 0, testing to see if they are not equal. The comparison, in turn, is followed
by one or more lines of JavaScript that should be executed if the comparison
is true; in our case, the single line that should be conditionally executed car-
ries out our subtotal calculation.
The else command, if supplied (it’s optional), is followed by one or more
lines of JavaScript that should be executed if the if comparison is not true;
in our case, if the comparison is false (that is, if qty.value is equal to 0),
then we shall set our text field’s value to an empty string: **.
“The net result of this change is that if the quantity field for an item is empty
(giving ita value of zero), then the txtSubtotal.0 field will be blank.
To apply the same effect to the txtTaxAmt fields, you should change their
value calculations to this:
var subtotal = this.getField("txtSubtotal.0*)
if (subtotal.value != 0)
event.value = glaxRate * subtotal.value
else
event .value =
This embodies exactly the same reasoning as the txtSubtotal.0 field, except
that we check to see if the value of txtSubtotal.0 is zero to decide whether to
put a blank into our tax field.
You should add the if.e1se block to all four of the txtSubtotal and
txtTaxAmt fields.54 EXTENDING ACROBAT FORMS WITH JAVASCRIPT.
if subotal snot
Predefined calculations
Unfortunately, any field that uses one of the predefined calculations, such as
‘our txtCost fields, will continue to be “0.0” if its value is 0. This is probably
the only reason to use a JavaScript when a predefined calculation would do.
If we want our txtCost.0 field to properly blank itself when it’s zero, we
need to calculate its value with a JavaScript, rather than the predefined sum:
var subtotal = this.getField(*txtSubtotal.0")
var tax = this.getField("txtTaxAmt.0")
if (subtotal.value != 0)
Helse
event.value = subtotal.value + tax.value
event.value =
This isa little more work than using the predefined calculation, but it does
give us the esthetic improvement of having zero-value totals appear blank.
“Global” Tax Rate
Let's say that, long after you have designed this form, the tax rate changes in
your locale. In our form, we use the tax rate (.08) to calculate the value of
the txtTaxAmt fields:
event.value = .08 * subtotal.value
‘Our form has four of these fields; in other forms, the tax rate could conceiv-
ably be used dozens of times, in fields scattered throughout a complex form,
Chasing down all of these references to the tax rate and replacing .08 with,
say, .09 would be tedious at best.
As it happens, it’s easy to initially design your form to make changing all the
references to the tax rate easy. We shall add a Document JavaScript to our
form that does just one thing: It defines a variable that contains our tax rate.
You may remember from Chapter 2 that variables defined in a Document
JavaScript can be used by any JavaScript in the Acrobat document. This
being so, any JavaScript in our form that needs to refer to the tax rate can
use the name of the tax rate variable, rather than using the numeric value
directly. If we later modify the Document JavaScript, changing the value5 | CALCULATING FORM FIELDS SB
assigned to the tax rate variable, all JavaScripts that use that variable will
use the new tax rate. In one blow, we will change the tax rate used through-
‘out our form.
Variables, such as our tax rate, that can be used throughout an Acrobat file
are referred to as global variables. Anything you define in a Document
JavaScript is global, that is, available to all the JavaScripts in the document.
Creating the Document JavaScript
You may want to review Chapter 2 for a detailed description of the behavior
and creation of Document JavaScripts in general. Here, we'll simply list the
steps for creating our specific JavaScript.
To create a Tax Rate JavaScript:
Start with the Acrobat document open and the Hand tool selected.
1. In Acrobat, select Tools > JavaScript > Document JavaScript.
Acrobat will present you with the JavaScript Functions dialog box.
2. In the Script Name text box, type TaxRate or some other descriptive
label (Figure 5.17).
3. Click the Add button.
Acrobat will present the standard JavaScript Edit dialog box with some
preliminary (and useless to our purposes) code already entered.
JavaSenpt Functions
=) ame
2) Ca...)
tae
Figure 5.17 We are
oing to add a Document
JavaScript called TaxRate
to our document. This
“| script will define a vark
able, gTaxRate, that holds
the tax rate to be used by
ail the other JavaScripts
in our Acrobat file.BB EXTENDING ACROBAT FORMS WITH JAVASCRIPT
5.
Delete the default code in the JavaScript Edit dialog box and type the
following:
var gTaxRate = .08
This one-line JavaScript creates a variable named gTaxRate and assigns
it the value .08 (Figure 5.18). (I always precede global variable names
with a lowercase g; this way, I know that when I see the variable name
used in other JavaScripts that it's a global variable, defined in a
Document JavaScript.)
a ki PRs
se this log to create an eat your InaSerot
ferstanae - 08
12, Col
Ge Ga) Ca
Figure 5.18 Our Document JavaScript is quite short.
It simply defines a single variable named gTaxRate.
Close all dialog boxes until you are back to the Acrobat document.
We have now created a Document JavaScript that creates our global variable
gTaxRate.
Using the global variable
Now we need to modify our four txtTaxAmt calculations so that they use
gTaxRate, instead of directly using the number .8.
‘As usual, I'll step us through changing txtTaxAmt.0 and let you modify the
other three txtTaxAmt fields.
To apply the new global variable:
Start with the form open in Acrobat and the Form tool selected.
1
2
3.
Double-click on txtTaxAmt0 to get to the Field Properties dialog box.
Go to the Calculate panel.
Click the Edit button next to the Calculation JavaScript.5 | CALCULATING FORM FIELDS 87.
You will now be looking at the JavaScript Edit dialog box displaying
our current JavaScript. This JavaScript defines the calculation as:
event.value = .08 * subtotal.value
4. Replace the .08 in the calculation with the name gTaxRate.
Your calculation line should now look like this (Figure 5.19):
event.value = gTaxRate * subtotal. value
ari Et
‘Use this dialog r create and edit your JvaScrit
a = ws peSCTIOTA OT
umtoutvae = 0)
‘rere aoe = gTanRate* rota vive
tn 6, col2
Ce ed CHD
Figure §.19 In our form field JavaScripts, we must use
the name of our global variable, aTaxRate, instead of the
actual numeric valve. If we later change the value of gTaxRate
in our Document JavaScript, this wil! automatically change
the tax rate used in all our calculated form fields.
5. Close all dialog boxes until you are back to the Acrobat document.
You should make the above change to all four of the txtTaxAmt calculation
JavaScripts.
Having done so, you will see no immediate change. After all, our tax rate
hasn't changed; we are simply getting to it from a variable rather than using
the number directly.
Change the tax rate
‘To see why this change has been a useful thing to do, suppose that your
area has had a tax rate change (an increase, presumably). To make all the
necessary changes at once, you need only change the value of gTaxRate in
the Document JavaScript.
To change the tax calculation for all the items in the form:
4. Select Tools > JavaScript > Document JavaScripts.
You will be looking at the JavaScript Functions dialog box.SB EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Figure 5.20 If you later
want to change the tax
‘ate used throughout your
form, simply go to the
JavaScript Functions dia-
og box, click on the
TaxRate script, and click
Edit. You can then change
the value assigned to the
gTaxRate variable.
2. Select the TaxRate JavaScript in the list (as we have in Figure 5.20) and
click the Edit button.
8. In the JavaScript Edit dialog box, change the tax rate to .09, or what-
ever other number appeals to you:
Var gTaxRate = .09
4. Exit all dialog boxes until you are at your Acrobat document.
. Examine the tax amount fields; all four of them will now contain calcu
lated values that reflect the new tax rate.
By changing the single tax rate value in the Document JavaScript, we
updated the tax rate used by all JavaScripts throughout our form. In this
case, there were only four such JavaScripts; in a larger form, there could be
many dozens.Auto-Entering
Form Data
One of the beauties of electronic forms is their ability to supply information
that the user would otherwise need to type in. For example, when the user
selects a product to buy in an electronic order form, the form should be
able to fill in the proper price per item and calculate the total cost
For this to happen, the form must contain a table of products and their
prices. Each time the user chooses a product, the form must look up that
item in the table and obtain the price of that item.
This is what we shall learn in this chapter: how to build a table of items and
prices in a form and then fetch information from that table to automatically
fill in form fields.@0 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Project
(Biles: Ch06_Example_1.pdf, ChO1_Example_1_Raw.pdf)
In this chapter, we shall link the combo box (Figure 6.1) in our order form
to the Price/ml field in the same form. When the user selects a new product
from the combo box’s menu, the form will change the price per milliliter to
reflect the chosen product and then recalculate the total cost (Figure 6.2).
Milk of Human Kindness
Bile of Regret
¥ Blood, Sweat. Tears
Figure 6.1. The form contains 2
Plasma of Siliness. list of prices for all the items that
Cell Scrapings of Height
appear in this combo box.
IMeraphoric Body Fluids, Inc.
Pace Ur Figure 6.2 The Price/mi and Total
flud Cost flelds always reflect the item
Querety i currently selected in the combo box.
Prewm $1000 When the user picks a new item, the
al cot secon rice per mitititer and the total cost
change to reflect the new item
Looking at Figure 6.3, we can see that this form has four fields: a combo
box (cboFluid) and three text fields (txtQuantity, txtRate, and txtTotal). The
field we most care about is the combo box; we shall be adding a JavaScript
to this field that changes the txtRate and txtTotal fields to reflect the user's
choice of fluid. Specifically this field must do three things when we pick an
item from its menu:
= Look up the price of that item.
= Set the value of txtRate to the item’s price.
= Recalculate the value of txtTotal.
Let's see how to do it,
Metaphosic Body Fluids, Ine.
Pace Use
od
Quay ih
Pricont Cm Figure 6.3. Our form has four
‘onl Cort (a) fields in it: @ combo box and
ms) three text fields.6 | AUTO-ENTERING FORM DATA 2.
The JavaScript
The Approach
In this program, we need to build a table of prices for the items in the
combo box menu. We shall do this with a JavaScript Array object. An Array
object represents a list—in our case, alist of prices. Each item in the list can
be looked up by its position in the list or by a keyword, a string that we
have associated with that value in the list. In our case, we shall use the
export value (see next section) of each item in the combo box as the key-
word we use to fetch that item’s price.
We need to write two JavaScripts for our form:
© A Document JavaScript that creates our table of prices. This script will
create an Array object and then load it up with pairs of export values
and associated prices.
= A JavaScript attached to our combo box that looks up the current
export value in the price table and uses the resulting price to set the
values of the txtRate and txtTotal fields.
Combo Box Export Values
Each item in a combo box's menu has two pieces of text associated with it:
The item text that actually appears in the pop-up menu.
= The export value that represents the combo box’s selected value when
the form data is exported to a file or submitted for processing,
The text and export value of each item in the combo box is set by the form
designer in the Field Properties dialog box (Figure 6.4).
If you examine the properties of our combo box, you will find there are six
items in the menu, with the following export values: MHK, BST, PS, BR,
GU, CSH. There is nothing magic about these values; I picked them just to
be rough abbreviations of the menu item text. (Thus, “MHK” is the export
value for “Milk of Human Kindness.”)
Our JavaScripts will associate each of these export values with the price per
milliliter of the corresponding product.@2 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
hem Bie ofReyiet ed
(p00 value: BF
Figure 6.4 Each menu
item in @ combo box has
two strings associated
with it: the item text that
appears in the menu and
acanereel | the export vatue that is
— used to report the user's
(Goea) (CEL) Selection when the combo
box’s data is processed.
asm of Sines
Cell Scraings of Heh
Creating the Price List Array
(Our first JavaScript is a Document script that creates our price list. This will
be an Array object containing paired export values and prices. Refer to
Chapter 2 for a full discussion of Document JavaScripts.
To create the Document Script:
Start with the form file open in Acrobat.
1. Select Tools > JavaScript > Document JavaScripts.
Acrobat will present you with the JavaScript Functions dialog box
(Figure 6.5)
< ea
Crea.
- snvasenotFuncions
Serge Name
Figure 6.5 The Java-
Script Functions dialog
if box is where you create
2) a Document JavaScript.
Type in a name for the
JavaScript ("PriceList” in
this example) and click
the Add button.2
3.
4.
Tis array wil con-
tan our price ist
[Hore we associate
export valves with
prices
8.
6 | AUTO-ENTERING FORM DATA 63
In the Script Name box, type the name “PriceList” or something simi-
larly descriptive.
Click the Add button,
Acrobat will present you with the usual JavaSi
taining some initial JavaScript code.
Edit dialog box con-
Remove the default JavaScript code and type in the following JavaScript
(Figure 6.6):
|_—var gPriceList = new Array // Create a reference to a new array
// Load the array up with prices for the products:
gPriceList[*MHK"] = 16 // MHK's price is $16/ml
gPricelist("@R"] = 12 // ...ete.
gPriceList(*8ST"] = 18
sPriceList ("GU") = 6
gPriceList(*Ps*] = 4
gPriceList["CSH"] = 72.50
JavaScript Eat
se tls dalog to create and edit your JavaScript
PPIceLn = pew Atay 7] Crete a etevece afew aay]
rceust Mac] 16] MURS Once B16 me
Ln 4, Col a7
Figure 6.6 You type your Document JavaScript into
the JavaScript Edit dialog box.
Click OK to exit all the dialog boxes until you are back at the Acrobat
page.
‘You won't see anything different in your form at this point. Our new
JavaScript creates a price list array, but we haven't yet used it to do
anything.EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The code in detail
var gPriceList= new Array
The JavaScript new command creates a new object, in this case, a new Array
object. We assign the newly created Array object to a global variable,
gPriceList, (created by the var command). Since this is taking place
within a Document JavaScript, gPriceList will be usable within any
JavaScript in our Acrobat file.
gPricelist[*MHk"] = 16
Here we associate prices with the export values in our combo box. An array
name (gPriceList) followed by a pair of square brackets enclosing a value
indicates one of the entries in the list. Inside the square brackets there may
bea number specifying the sequential position within the list of the partic-
ular item we want, or a string in quotes indicating the keyword associated
with the desired item.
In our case, we are assigning a value to the MHK entry in the list. The above
line of JavaScript, translated into English, says, “In the array gPriceList
assign the number 16 to the keyword MHK.”
We repeat this for all six of the export values in our combo box.
Formatting Your Code
JavaScript Is pretty forgiving about letting you add spaces or tabs to make your code read-
able. You can indent your JavaScript any way you wish to improve how well the eye scans
It. For example, | usually indent the statements that follow if commands to emphasize
the fact that they will be executed only if the comparison is true:
if (event changeéx in gPriceList)
rateFld.value = gPriceList [event .changeEx]
Similarly, | usually use some combination of tabs and spaces to separate my comments
from the executable JavaScript code; | also try to make them line up:
gPriceList[*MHK"] = 16 J] MHK's price is $16/mliyr
gPriceList[*BR"] = 12 J] ste.
This makes them more readable and is, to my eye, more esthetically pleasing.
‘You may double-space your JavaScript statements and add spaces and tabs as you wish.
Your goal should be to make your programs as readable as possible. This Is a service not
only to other people, but to yourself when you return to your programs months later.© | AUTO-ENTERING FORM DATA 65
Creating the Combo Box Script
Now we need to teach our combo box how to look up export values and do
something useful with them.
‘We are going to attach a keystroke JavaScript to our combo box. This is a
JavaScript that is executed every time the user types a character into the
combo box. Surprisingly, this script also gets called anytime the user picks
an item from the combo box’s menu.
So when the user picks an item from the combo box menu, Acrobat will
execute our keystroke JavaScript, which will do our table lookup, change
the value of txtRate, and, finally, calculate a new value for txtTotal.
‘To attach the keystroke JavaScript to our combo box:
Start with the form open and the Form tool selected.
1. Double-click the combo box to get to its properties.
Acrobat will present you with the Field Properties dialog box (Figure 6.7).
Ga) CD
Figure 6.7 You create a keystroke JavaScript by double-
clicking the combo box and then going to the Format
panel in the resulting Field Properties dialog box.
2. Go to the Format panel.
3. Select Custom in the Category list.@6 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
4. Click on the Edit button next to the Custom Keystroke Script text box.
‘You will now be looking at the JavaScript Edit dialog box (Figure 6.8).
5. Type in the following script:
// Get references to our form fields.
references 10 var rateFld = this.getField(*txtRate")
sree ee we var totalFld = this.getField(*txtTotal*)
var quantityFld = this.getField(*txtquantity")
// Is the new export value a keyword in our price list?
‘our export value |_T if (event. changeEx in gPriceList)
rateFld.value = gPriceList [event changetx]
J] Now calculate a new value for the total price
[Feermetthe price | totalFld.value = quantityFld.value * rateFld.value
savaScrit tit
Use tis dialog to create ang edit your JavaScript
Tres =the pao
‘ora = tus geFtocveTeta
Guana tas etic Quarey)
fe ever cnangees in gece
‘eric waue = gosceustlevert changes)
rae ate » quero wave * rated value
Wn. c0l2
Cael) Cm) Co)
Core) (Gare) (oe
Figure 6.8 Type your keystroke JavaScript into
the JavaScript Eat dialog box, as usual.
6. Click OK to close all dialog boxes.
7. Try it out: Select various items from the pop-up menu and watch the
Price per milliliter and total cost fields change value.6 | AUTO-ENTERING FORM DATA 67.
The code in detail
var rateFld = this.getField(*txtRate")
var totalFld = this.getField(*txtTotal")
var quantityFld = this.getField(*txtQuantity")
‘This script starts by getting references to the three text fields we need to
access, placing those references in appropriately named variables.
‘if (event.changeEx in gPriceList)
We are here executing a JavaScript 1f command that checks to see if the
new export value is a valid keyword in our gPriceList array. In a keystroke
JavaScript for a combo box, event .change€x refers to the export value of the
newly selected menu item. The phrase (Event.changeEx in gPriceList)
translates into: “Is there a keyword matching our export value in the Array
object gPriceList2”
rateFld.value = gPriceList[event.changeEx]
This is the line of JavaScript that if executes if event .changeEx is a key-
word in gPriceList.
The phrase gPriceList [event .changeEx] fetches the value in the gPriceList
array that is associated with the export value. Put differently, the phrase
gives us the price of the item currently selected in the combo box. We set
the value of the txtRate field to this number. The txtRate field will immedi-
ately display the new price per milliliter.
totalFld.value = quantityFid.value * rateFid.value
Finally, we change the value of the txtTotal field (residing in the total Fld
variable) to the product of the quantity and rate. The latter two numbers we
obtain from the txtQuantity and txtRate fields.68Roll-Over Help
Every well-designed form needs some mechanism by which it prompts the
user on how to fill out the form. The most common way of doing this in
Acrobat is via the fool-tip help that is built in to the Acrobat form mecha-
nism, (Any text you enter into the Short Description field in the Field
Properties dialog box becomes tool-tip text for that field.) In this chapter,
we shall see how to implement an alternative: roll-over help. This is text that
automatically appears when the mouse pointer enters a form field; there is
no half-second pause, as with tool-tip help. The use of roll-over help, rather
than tool-tip help, is purely an esthetic decision, based on how you want
your form to “feel” to the person who fills it out.7O EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Project
(Files: ChO7_Example_l.pdf, ChO7_Example_1_raw.pdf)
‘We are going to add roll-over help to the text fields in the form in Figure 7.1
Whenever the mouse pointer moves over one of the text fields, a bit of
help text will appear in the large blue area at the bottom of the form, as
in Figure 7.2.
Ap eats fou Eupleyucnr
se)
vaste ,
el
tt es
Figure 7.1 We are going
to add roll-over help to the
text fields in this form.
FY Figure 7.2 When the mouse
pointer moves over a text field
Een Ades (top), descriptive text will appear
== inthe Bue area atte btm of
the form (shown below).
There are five text fields in this form (Figure 7.3). The top four collect data:
the name, address, nickname, and email address of the applicant; the bot-
tom field, txtHelp, is an invisible text field perched over the blue rectangle
that is part of the form design
Application for Euploy went
‘wee EE
FullAddnes
=
Nidwous CXR] Figure 7.3 Our form has five
teil Adites [EEE] text fields. We shail use the bot
tom field to display our help text
for each of the four fields above.7 | ROLL-OVER HELP 72,
‘The txtHelp field is invisible not because the Hidden attribute is selected in
the Field Properties dialog box, but because it has no background or border
color (Figure 7.4) and no initial text init. t will become visible only when
it has text to display.
Figure 7.4 These are the
‘Appearance properties for our
help text form field. Note that
there is no background or bor-
der; this means that the field is
not visible if it has no text in it.
To make our roll-over help, whenever the mouse pointer enters one of the
four data-gathering text fields, a JavaScript in that field will place appropriate
help text into the txtHelp field. When the pointer leaves the text field, that
field's JavaScript will remove the text from txtHelp.
The JavaScript
The Approach
‘We are going to need two JavaScripts for each of the four text fields:
= A JavaScript attached to the field’s Mouse Enter event that puts appro-
priate help text into the txtHelp field
Remember that the Mouse Enter event occurs when the mouse pointer
passes into the boundary of a form field.
= A JavaScript attached to the field's Mouse Exit event that removes the
text from txtHelp
Remember that the Mouse Exit event occurs when the mouse pointer
passes out of the form field again.72 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The Code
Here we shall attach the JavaScripts to the txtName field. To complete the
form, you will need to carry out these same steps for each of the remaining
data-gathering fields.
Start with the form open in Acrobat and the Form tool E| selected.
4. Double-click the txtName field to gain access to its properties (Figure 7.5);
g0 to the Actions panel of the Field Properties dialog box.
Figure 7.5 The Actions
panel of the Field Prop-
erties dialog box is where
‘you attach a JavaScript to
2 text field.
2. Inthe “When this happens” box, select Mouse Enter and then click the
Add button.
Acrobat will present you with the Add an Action dialog box (Figure 7.6).
Figure 7.6 The Add an
Action dialog box lets you
attach an action to a form
field. ur action will create
2 JavaScript to add help
text to the Name field.Get reference to
help eld
Sets value to
help text
7 | ROLLOVER HELP 73,
3. Select JavaScript in the pop-up menu and then click the Edit button.
Acrobat will present you with the JavaScript Edit dialog box (Figure 7.7).
Figure 7.7 You type your JavaScript into
the JavaScript Edit dialog box.
4. Type the following in the JavaScript Edit dialog box:
[-~1var helpText = this.getField("txtHelp")
|_—helpText.value = "what's your full name?"
&. Click OK to return to the Add an Action dialog box . Click the Set
Action button, placing yourself back at the Actions panel.
There is now a bullet next to the Mouse Enter event, indicating there's
an action associated with that event (Figure 7.8).
Mowe UP
a Figure 7.8 When you return to the
Momba | Actions panel, there will be a bullet by
OnBir the Mouse Event, indicating that this
event has an action assigned to it.
6. Repeat steps 2 through 5 for the Mouse Exit event, typing this
JavaScript into the JavaScript Edit dialog box:
var helpText = this.getField("txtHelp")
helpText.value = ""
7. Close all dialog boxes until you are back at the Acrobat page.
8. Tryit out: Click the Hand tool, then pass the mouse pointer over the
‘Name field; you should see your help text appear in the blue box.
You will want to repeat these steps for the txtAddress, txtNickname, and
txtEmail fields, using appropriate help text for each.74 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
The code in detail
Let’s look first at the Mouse Enter JavaScript:
var helpText = this.getField("txtHelp")
We start by getting a reference to our help text field, txtHelp. We assign this,
reference to the variable hel pText.
helpText.value = "What's your full name?"
We now set the value of the helpText field to our help text, “what's your
full name?" The value of a text field is the text that it displays to the user.
When we set the field’s value, we cause it to immediately display that text. In
‘our case, this script causes the help text to appear when the mouse pointer
centers the txtName field.
‘The Mouse Exit JavaScript is almost identical to the Mouse Enter script:
var helplext = this.getField("txtHelp")
helpText.value = ""
It gets a reference to the txtHelp field but this time sets its value to *". Open
and close quotes together, with nothing in between, indicates “no text” The
txtHelp field displays no text and, therefore, effectively disappears again
when then mouse pointer leaves txtName.
Enhancement
(Files: ChO7_Example2.pdf, Ch07_Example2_raw-pdf)
Our roll-over help in its current state works very well. If there is anything to
complain about, it would be that our bits and snippets of help text are dis-
tributed among all of our text fields; if we wanted to rewrite the help
entries—say, to translate them into Spanish—we would have to chase them
down and change them one by one.
It would be helpful if we could collect all of the help text strings in one
place, for ease of maintenance and modification. We can do this by placing
them all in a JavaScript Array object. You may remember from Chapter 6
that an Array object embodies list in your JavaScript code—in our case, a
list of help text strings.7 | ROLL-OVER HELP 78
We shall create our array of help text in a Document JavaScript so that it
will be usable from within every other JavaScript in our document. In par-
ticular, our Form Field JavaScripts will be able to use strings from the array,
rather than have the text in quotes within the Field script itself,
We need to do two things to implement this new method:
= Write a Document JavaScript that creates an Array object containing all
the appropriate help text,
= Modify the Mouse Enter JavaScripts in all of our form fields so that
they use help text from this global array (“global” because the array is
accessible throughout our form).
This modification is completely optional, but it pays off in the long run,
particularly with large, complex forms that have lots of roll-over help text.
The Document JavaScript
To create the new Document JavaScript, start with the form file open in
Acrobat and do the following:
4. Select Tools > JavaScript > Document JavaScripts.
Acrobat will present you with the JavaScript Functions dialog box
(Figure 7.9).
Figure 7.9 The JavaScript
Functions dialog box is where you
create a Document JavaScript.
‘Type in a name for the JavaScript
(-HelpText,” above) and click the
‘Add button.76 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
2. Inthe Script Name box, type the name “HelpText” or something simi-
larly descriptive.
Remember that all Document JavaScripts must have names.
3. Click the Add button.
Acrobat will present you with the usual JavaScript Edit dialog box
(Figure 7.10) containing some initial JavaScript code.
Figure 7.10 You type your Document JavaScript
into the JavaScript Edit dialog box.
4. Replace the default JavaScript code with the following JavaScript; this
script creates an array and loads it up with strings all at once; we'll dis-
cuss it in more detail in a moment:
var glelpText = [ // Create a variable, gHelpText
“what's your name?", // String 40
"where do you Tive?", // String #1
“What may we call you in the office?", —// String #2
“What's your email address?" J/ String #3
]
5. Click OK to exit dialog boxes until you are back at the Acrobat page.
‘You won't see anything different in your form at this point. Our new
JavaScript creates a list of help text strings, but the form doesn't yet do
anything with it. We'll teach our form to use the new array in a moment,
but first, a look under the hood of our JavaScript.7 | ROLL-OVER HELP 77
The code in detail
var gHelpText = [...]
Although it’s not immediately obvious, this Document JavaScript has only
one JavaScript statement in it: the statement that creates an array and loads
it up with a list of values. The var command creates a variable, as usual—in
this case, named ge]pText. (The initial g in the name indicates this is a
globally accessible variable; that’s my own naming convention, not a
JavaScript requirement.)
When the name of the variable is followed by a pair of square brackets, as in
this case, the var command creates the variable as an array and places into
the array the list of items it finds inside the brackets:
C
“What's your name?*,
“where do you live?*,
“what may we call you in the office?",
“what's your email address?"
]
In this case, the array is filled with a list of strings, each a little piece of help
text for one of our form fields.
This is all our Document JavaScript needs to do. The gHelpText array is
now a repository for all our help text. Other JavaScripts can get to these
strings using the following syntax:
gHel pText (2)
‘The number in the brackets is the sequential position within the array
gke1pText of the string that we want, Items within an array are numbered
from zero, so that gHe1pText [0] will refer to the string "What's your
name?" in our list.
New Form Field JavaScript
Now that we have created a globally available array of help text, we need to
teach our form field scripts to use it. Specifically, in each of our text fields,
we need to change the script we associated with the Mouse Enter event.TB EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Here is the new version of the Mouse Enter JavaScript for the txtName field:
var helpText = this.getField("txtHelp")
helpText.value = gHelpText (0)
This is identical to our earlier Mouse Enter script, but for one change: In
the second line of code, we set the value of the text field to string number 0
in the gHe1pText array ("What's your name?"), rather than having the string
directly in this script in quotes, as we did earlier.
We need to change each of the Mouse Enter JavaScripts in our text fields,
using the appropriate numeric position for each field’s help text.
To a user, our form will look no different than it did before. However, making
future changes to our help text (to support other languages, for example) will
bbe much easier, since all of the text resides in one place in our form.
‘Trust me, for a complex form, you'll ind this technique very useful.Dynamic Form Fields
One of the most common “special effects” in Acrobat forms is the revealing and
hiding of form fields based on responses to other form fields. For example, click
oon a check box marked “self-employed” and a series of text fields may appear,
asking for your business name, federal taxpayer ID, and other related informa-
tion; if you uncheck the box, the text fields all disappear.
1 refer to this effect as the progressive display of the form's fields. The fields
are not all initially visible; the hidden fields are revealed to the user only as he
or she selects choices from the visible controls.
In this chapter and the next, we are going to see how to do this. This chap-
ter will present a technique for toggling the visibility of a relatively small
number of form fields. In the next chapter, we shall see how to make whole
pages of form fields appear on command.80 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Project 1: Attaching the
JavaScript to a check box
(Files: ChO8_Example1 pdf, Ch08_Examplel_raw.pdf)
We are going to add progressive display to the form pictured in Figure 8.1.
Initially, the only control visible to the user is the check box. When the user
selects the check box, two combo boxes and a button are revealed, allowing
the user to specify a genre and a movie and submit the request (Figure 8.2).
If the user deselects the check box, then the combo boxes and the button
disappear again,
CONTINENTAL
DIVIDE Acme
I 1]
CO Yes! Send me my free DVD! riure 81. We ore
going to add progressive
display of the form fields
In this Acrobat docu-
ment. Initially, the onty
form field visible is the
check box.
NIT Beane al Lia
CONTINENTAL
DiViIDE Acme
1 Yes! Send me my free DVD!
Figure 8.2 When the
user clicks on the
check box, a JavaScript
attached to that contro!
makes the other fields
In the form visible.8 | DYNAMIC FORM FIELDS 82
Figure 8.3 shows the form fields in our Acrobat file. There are four of them:
m= chkYesis the check box that lets the user declare a desire for a free DVD.
= choGenre is a combo box from which the user can select a genre.
= choTitle is a combo box from which the user can select a title.
= binSubmit is a standard submit-data button.
Of these, only chkYes is visible when the document is first opened; the
others all have their visibilities set to hidden (in the Field Properties dialog
box). The other fields will become visible as a result of JavaScripts we shall
write,
CONTINENTAL
DiViDE 4aa—
Yes! Send me my free DVD!
Figure 8.3. Our sample
form has four fields, of
which only the check
box is initially visible.
The JavaScript
Approaching the Problem
Conceptually, this is a pretty easy problem. Every form field has a Boolean
(true/false) property named hidden that determines whether that field is
visible or not; if the hidden property is set to true, then the field is not visi-
ble to the user.
We need to write a JavaScript that toggles the hidden attribute of the two
combo boxes and the button. We shall attach this JavaScript to the Mouse
Up event for the check box field. The JavaScript will look to see if the check
box has been selected or deselected. If the check box is selected, then the
JavaScript will set the other fields’ hidden attribute to false, making them82 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
visible to the user; otherwise, the script will set the hidden attribute to true,
hiding the other fields.
How can our JavaScript tell if the check box is selected or not? We can look
at the export value of that field, (The export value of a check box is the value
that the field has if the check box is selected.) When I created this form, I set
up the check box so that its export value is the string “Yes” (Figure 8.4). Our
JavaScript has only to look at the check box’s value property to see if itis
“Yes” and then set the other fields’ hidden property appropriately.
Figure 8.4 The check box has
an export value of *Yes"; this
is part of the design of the
form when | first created it.
The check box script
To attach the JavaScript to the check box:
Start by going to the Actions panel of the Field Properties dialog box
(Figure 8.5) for chkYes check box. (See Chapter | for a reminder of how
to get there.)
2. Select the Mouse Up event and click the Add button.
‘You will now be looking at the Add an Action dialog box.
2. Select the JavaScript option in the pop-up menu and click the Edit
button.
Acrobat will present you with the usual JavaScript Edit dialog box.8 | DYNAMIC FORM FIELDS 83
Figure 8.5 The JavaScript
that toggles the other form
fields is attached to the
cchkYes check box, associ-
ated with the Mouse Up
event.
3. ‘Type the following script into the JavaScript Edit dialog box (Figure 8.6):
var genreFld = this.getField("cboGenre")
var titleFld = this.getField("cboTitle")
var submitBtn = this.getField("btnSubmit")
form fields
if (event. target.value
‘check box is genreFld.hidden = false
Yes") {
recerictgl titleFld.hidden = false
submitBtn.hidden = false
}
else {
ide genreFld.hidden = true
frees titleFld.hidden = true
submitBtn.hidden = true
geeFtela(cboGence™>
geetaeld(roboTit le")
Figure 8.6 You type
your JavaScript into the
JavaScript Edit dialog
box, as usual.84 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
4. Exit from all the dialog boxes until you are once again looking at your
Acrobat page.
8. ‘Try it out: Return to the Hand tool and click on the check box; all the
‘other form fields should appear on the page. Uncheck the box, and
the other fields will disappear.
The code in detail
var genreFld = this.getField(*eboGenre")
var titleFld = this.getField(*cboTitle")
var submitBtn = this.getField("btnSubmit")
We start by getting named references to the three form fields whose visibili-
ties we are going to manipulate. We need these references in order to gain
access to their hidden properties.
Remember that you can make up whatever names you wish for variables. 1
made up the names genreFd, titleFld, submitBin; to me they're descriptive
and yet reasonably short. You can choose any names you wish, as long as the
names don't already have meaning to JavaScript. (Naming a variable +f, for
example, would not work; JavaScript would interpret it as part of an if-else
statement.)
if (event.target.value == "Yes") — {
We execute the if command, which looks to see if the value of our check
box is “Yes.” If so, then if executes the JavaScript lines in the braces follow-
ing the parenthetical comparison. (Remember that double equals signs
mean és equal to.)
‘The phrase event target value may look odd at first, but it becomes clear
if you nibble at it left to right. You may remember from earlier chapters that
event. target is a reference to whatever form field triggered this JavaScript;
in this case, the target of the event is our check box. Since event. target is
‘our check box, event . target value is the value of our check box. This value
will be “Yes” (the check box’s export value) if the check box is selected.
genreFld.hidden = false
titleFld.hidden = false
submit8tn.hidden = false8 | DYNAMIC FORM FIELOS 85
Here's where we make our two combo boxes and the Submit button visible;
‘we do this by setting their hidden attributes to false. (Since they're not hid-
den, they must be visible, no?)
else {
genreFld.hidden = true
titleFld.nidden = true
submit8tn.hidden = true
}
‘The else command specifies what should happen if the earlier 1 compari-
son was not truc; in our case, this would be if the check box is not checked. If
the earlier comparison is not true, then e1se executes the JavaScript lines in
braces, setting the fields’ hidden properties to true, making them disappear.
Project 2: Attaching the
JavaScript to a combo box
(Fil
In this chapter's second project, we are going to see how to use a combo box
to display and hide other form fields.
If you look at the file Ch08_Example2.pdf, you will see it looks much like
our earlier example; I saved this file with the check box already selected, so
that when you open the file, it will look like Figure 8.2. In this project, we'll
examine how the items in the lower combo box change according to the
genre you select in the top combo box (Figure 8.7). If you pick Westerns in
the top combo box, the lower one presents you with three Westerns from
which to choose.
‘Ch08_Example2.pdf, ChO8_Example2_raw.pdf)
Se
Figure 8.7 In our second project, the movies shown
in the lower combo box will change according to the
Kenre the user selects in the upper combo box.86 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Figure 8.8 shows our combo boxes as they appear with the Acrobat Form
tool selected. The upper combo box, cboGenre, has three items in its menu:
Current Hits, Music DVD, and Westerns; when I created this control, I gave
these items the export values CH, MS, and WS, respectively. (You create a
combo box’s menu items and export values in the Options panel of the
Field Properties dialog box.)
= Figure 8.8 The lower combo box
in our form is really three combo
= boxes—only one of which is visible—
Stacked atop one another.
‘The name of the lower combo box looks a bit jumbled in Figure 8.8; this is
because it actually consists of three combo boxes placed on top of one another,
one for each of the genres. Only one of these will be visible at any time; the
other two will have their visibility controls set to hidden in the Field Properties
dialog box. These combo boxes have the names cboTitleHit, cboMusic, and
choTitle Westerns
When the user makes a selection from cboGenre, that control will determine
which item the user chose and then change the visibilities of the three stacked
‘combo boxes so that the corresponding control is visible and the other two
are hidden, For example, if the user chooses Westerns for the genre, then the
JavaScript attached to the cboGenre control will make cboWesterns visible
and hide the other two combo boxes.
The JavaScript
‘We shall attach our JavaScript to the cboGenre field as a keystroke JavaScripts
Acrobat will execute this script every time the user types a keystroke into the
field. In a combo box, a keystroke JavaScript is also executed whenever a user
selects an item from the combo box's menus; this is what makes the keystroke
JavaScript the perfect place to put our “enable proper movie list” script.
In a keystroke JavaScript for a combo box, the event .change£x property
holds the export value of the menu item the user selected. We are going to
compare event .change€x with each of cboGenre's export values in turn;
when we find a match, we shall then set the hidden property of the other
three combo boxes.8 | DYNAMIC FORM FIELDS
The combo box script
Toattach the keystroke JavaScript to the combo box:
Start with the Form tool selected and the Field Properties dialog box dis-
playing the Format panel for cboGenre. (See Chapter | for a reminder of
how to get to the Field Properties dialog box.)
1. Click the Edit button for the Custom Keyboard Script (Figure 8.9).
‘Acrobat will present you with the JavaScript Edit dialog box.
Figure 8.9 For @ combo
box, you want your
JavaScript to be a key-
stroke JavaScript. Acrobat
will execute this script
every time the user picks
an item from the combo.
box's menu.
2. Type the following script into the JavaScript Edit dialog box.
// Get references to our three combo boxes
his.getField("cboTitleHit")
var hits
var music « this.getField("cboTitleMusic")
var westerns = this.getField("cboTitlewesterns")
// Has the use selected “Current Hits?"
‘if (event.changeEx == "CH") — {
hits.hidden = false
music.hidden = true
westerns. hidden = true$B EXTENDING ACROBAT FORMS WITH JAVASCRIPT
// Was the user selected "Music DVDs?"
else if (event.changeEx == "MS") — [
hits.hidden = true
music.hidden = false
westerns. hidden = true
}
J/ Has the user selected "Westerns?"
else if (event.changeEx == "WS") — {
hits.hidden = true
music.hidden = true
westerns.hidden = false
}
3. Exit out of all the dialog boxes until you are once more at the Acrobat
Page.
4. Try it out: Using the Hand tool, select different genres from the top
combo box; the second combo box will change with each genre.
Let's look at what we've done here.
The code In detail
var hits = this.getField(*cboTitleHit")
var music = this.getField("cboTitleMusic")
var westerns = this.getField("cboTitleWesterns")
We start by getting references to the three combo boxes whose visibility we
want to control. We assign each combo box object to an appropriately
named variable. (Again, I picked these variable names myself; there's noth-
ing special about these names.)
if (event.changeEx == "CH") —[
Here we have a call to the if command that compares event .changeEx,
which contains the export value of the item the user selected in cboGenre,
with the string “CH, which is the export value for the Current Hits menu
item. As always, if the comparison is true, then if will execute the JavaScript
lines in braces.
hits.hidden = false
music.hidden = true
westerns. hidder8 | DYNAMIC FORM FIELOS 89
If the if comparison is true—that is, if the user selected Current Hits in the
Genre combo box—then we will make the hits object (the cboTitleHit
combo box) visible by setting its hidden attribute to false. We shall also set
the hidden attribute of the other two combo boxes to true, hiding them
from view.
else if (event.changeEx == "MS") — {
hits.hidden = true
music.hidden = false
westerns.hidden = true
)
If the first if comparison is false—if the user didn’t select Current Hits—then
wwe shall check to see if they selected Music DVD; we compare event .change®x
with “MS. the export value for the Music DVD item in our Genre combo box.
As before, if the comparison is true, then we make visible the Music DVD
combo box, cboTitleMusic, and hide the other two.
else if (event.changeEx == "WS") {
hits.hidden = true
music.hidden = true
westerns.hidden = false
,
Finally, we check to see if the user selected Westerns as their genre, showing
the cboTitleWesterns combo box and hiding the others.
JavaScripts for Other Control Types
As,you can see, the principle behind creating a small number of dynami-
cally visible form fields is pretty straightforward: You attach a JavaScript to
the controlling form field that sets the hidden attribute for the fields you
wish to manipulate. The JavaScript may need to determine the value of the
controlling field in order to decide which controls to make visible and
which to hide, as we did with our combo box.
Our two examples attached controlling JavaScripts to a check box and a
combo box. We shall finish this chapter by briefly reviewing how to use
other form types as the controlling field. We shall not step through any of
these in detail, but an example of each is among this chapter's sample files.90 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
List Box
Using a list box field to control other fields’ visibility is nearly identical to
using a combo box. In fact, the JavaScript for a list is identical to the
JavaScript you would use in a combo box. In both cases, the event .changeE»
property will contain the export value of the item the user selected; we can
examine this property and then alter other fields’ visibility accordingly.
‘The difference is that the JavaScript for a list box field must be attached to
the field’s Selection Change event, rather than being a keystroke JavaScript.
‘The Selection Change JavaScript is accessible through a panel in the list box
field’s Field Properties dialog box (Figure 8.10). Select the “This script exe-
cutes...” radio button, click the Edit button, and type your JavaScript into
the resulting JavaScript Edit dialog box.
Figure 8.10 The JavaScript
for a list box field should be
attached to the lists Selection
‘Change event, which is acces-
sible in the Field Properties
dialog box.
The file ChO8_Example3.pdf demonstrates how to use a list box field to
control the visibility of other fields. This is our same order-a-movie form,
but the user picks a genre from a list (Figure 8.11).
Radio Buttons
The JavaScript that controls fields’ visibility from within a set of radio but-
tons is nearly identical to that we used with our original check box. You will
attach a JavaScript to the Mouse Up event for each radio button in a set; the
script for each radio button is responsible for making visible and hiding the
controls associated with the choice that button represents.8 | DYNAMIC FORM FIELDS 94
CONTINENTAL
DiViDE Acaem
™) Yes! Send me my free DVD!
Figure 8.11 Here is a list
box field that controls the
visibility of our stacked
combo boxes.
For example, Figure 8.12 shows our form, now changed so that the user
picks a genre from among a series of radio buttons. (This file is
Ch08_Example4.paf in this chapter’s sample files.)
CONTINENTAL
DiViDE acm
1 Yes! Send me my free DVD!
Ogun — @aeeovoe Owen
Figure 8.12. This form
cemonstrotes 2 set of
radio buttons that con-
trols the visibility of our
stacked combo boxes.
The script attached to the radio button labeled Westerns makes the
cboTitleWesterns combo box visible and hides the others:
var hits = this.getField(*cboTitleHit")
var music = this.getField("cboTitieMusic")
var westerns = this.getField("cboTitleWesterns")
hits.hidden = true
music.hidden = true
westerns.hidden = false92 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Buttons and Text Fields
If you use a button field to control other fields’ visibility, as in Figure 8.13, you
will set up the button exactly as we did the radio buttons. You will attach a
Mouse Up JavaScript to the button that sets the hidden property of whichever
form fields the button must control. Examine the file Ch08_Example5.pdf to
see Figure 8.13's form in action.
CONTINENTAL
DIVIDE Antrim
|Current Hits a
Figure 8.13 The button
in this form controls the
Mf siti ofan the otner
controls in the form.
Text fields are usually inappropriate for use as a controlling form field.
Although you can attach a JavaScript to the field’s On Blur event that alters
the hidden property of other fields, the fact that a text field allows the user
to type in anything they wish usually makes for difficult script writing. You
need to accommodate any random input, and the code for this can get
messy. Usually, you want to limit the user's input to a set of known entries
(Current Hits, Westerns, and so on), and for this a combo box works much
better than a text field.Dynamic Controls
with Templates
In Chapter 8, we saw how to make a set of form fields appear as the result of
some user action: clicking a check box, selecting an item from a combo box,
and so on. We did this with a JavaScript that directly manipulated the fields’
hidden property. This technique is appropriate if we're managing the visibil-
ity of a small number of controls, but it becomes burdensome if we need to
manipulate a large number.
Acrobat provides a mechanism specifically for dynamically adding controls
and even entire pages to an Acrobat form: templates. A template is a page in
an Acrobat file whose contents—form fields, text, graphics—can be added
bya JavaScript either to an existing page in the file or to a new page that’s
inserted in the document. The process of adding a template’s contents to
a document, either as a new page or as an addition to an existing page, is
referred to as spawning the template.
A template page can be made so that it's initially invisible; the template
items will appear to the user only when the template is spawned.94 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Using templates to create dynamic forms has two advantages over directly set-
ting the dynamic fields’ hidden properties, as we did in the previous chapter:
= A template can have as many form fields on it as needed; spawning a
crowded, full template is no harder than spawning one with just a few
items. This makes templates more appropriate for managing a large
number of dynamic fields,
= Spawning a template adds everything on the template page to the docu-
‘ment, including artwork, text, labels, and images, as well as form fields.
We couldn't do that with the last chapter's technique, since only form
fields have a hidden property.
‘What do we lose by using a template? Once you have spawned a template,
there is no easy way to remove those items again; there is no “unspawn”
feature. With templates, as elsewhere in life, spawning works in one direc-
tion only.
In this chapter, we shall see how to create templates and add their contents
toa form.
The Project
(Files: ChO9_Examplel pdf, Ch09_Examplel_Raw.pdf)
In this chapter, we shall be working with the three-page PDF file in Figure 9.1.
We are going to convert pages 2 and 3 into invisible templates; when the user
first opens the fil, it will look like a single-page file consisting of only page 1.
200 cumeoene oe oneeemene 000 cuemnmee
CONTINENTAL CONTINENTAL
DiViDe Aan BViDe som
Yes Send we ry free BY) New we need yar odors
wrerurdetmareceywvers Ne
= 4 iy
Which mde maya he? syete
Telephone
where 5 —.
yr fe cote Are we geet, er what? Tae
Figure 9.1 Our sample document for this chapter has three pages. Were
‘Boing to turn the second and third pages into templates whose contents will
‘become visible only when the user clicks on the first page's check box.© | DYNAMIC CONTROLS WITH TEMPLATES 98
When the user clicks the Yes! check box, a JavaScript attached to that con-
trol does two things:
= It spawns the page 2 template, adding its contents to page 1 of the form.
= It spawns the page 3 template as a new page added to the end of the form.
‘What the user sees is that, upon selecting the Yes! check box, two combo boxes,
a text field, a button, and their labels appear on the current page (Figure 9.2)
and a second page suddenly appears that gathers shipping information. Try
this out with the sample file Ch09_Examplelpdf; it’s fun to watch.
@ OO Cni2 Continenal OVIDE-Dét
CONTINENTAL
DiViDE Actua
Yes! Send me my free DVD!
What kind of movie do you want?
\Westerns >|
Which movie would you like?
Tee sn 7
Ll Figure 9.2. The form
What's your offer code? — fields that were originally
on page 2 of the template
are added to page 1 when
Mie se setts ne ves
check box.
The JavaScript
We shall add a Mouse Up JavaScript to the check box on page | that spawns
two templates, as described above, Before we can do this, however, we need
to create those templates; this entails going to pages 2 and 3, one at a time,
and telling Acrobat that these pages should be treated as templates.
‘You may find it particularly useful in this chapter to open the file
‘Ch09_Examplel_Raw.pdf and follow along with the instructions as we first
create the templates and then attach our JavaScript to the check box.96 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
Creating the Templates
‘We want to turn both pages 2 and 3 in ChO9_Examplel_Raw.pdf into tem-
plates. Let's start with page 2.
‘To turn page 2 into a template:
Start with the Acrobat file turned to page 2.
4. Select Tools > Forms > Page Templates.
Acrobat will display the Page Templates dialog box (Figure 9.3). This
dialog box lists all templates defined in the Acrobat file. The list initially
will be blank.
__Pase Templates _
sane (emeneito———]
Figure 9.3. The Page Tem-
cere lates dialog box lets you
create, modify, and otherwise
Comme)
Cere) _ manage the list of templates in
the current Acrobat document.
2. Type a name into the Name field at the top of the dialog box.
This will become the name of the page 2 template within the docu-
ment. Pick something descriptive of the template’s contents. (I chose
tptMovielnfo; the “tpt” prefix will remind me later that this is the
name of a template.)
3. Click the Add button and then click Yes in the resulting confirmation
dialog box.
Acrobat will turn this page into a template with the specified name; the
name will now appear in the Page Templates list (Figure 9.4). There
will be a bullet to the left of the name; this indicates whether the tem-
plate initially wil be visible in the form. If you click the bullet, it will
toggle between a bullet, indicating the template is visible, and a minus
sign, meaning it's invisible.@ | DYNAMIC CONTROLS WITH TEMPLATES ST
Templates, Figure 9.4 When you create
ene (7 Sere ees oe
{ist in the Page Templates dia-
centres | xe {og box. The bullet to the left of
the template name indicates
whether the template is ini-
ally visible (+ ) or invisible (_).
4. Click the bullet, setting it to a minus sign.
‘As soon as you change the bulllet to a minus sign, page 2 disappears
from your document. It’s actually still there; i's just become an invisible
template within the PDF file. (You will notice that even the status bar at
the bottom of the page now reports one less page in the document; to
Acrobat, templates do not count as pages unless they're visible.)
Usually, you'll want your templates to be invisible initially. You would
leave them visible if you always wanted a page with those contents as,
part of the form; in that case, spawning the template would add
another instance of a page that already exists. For example, in an
expense report form, you would always want to have a page with
expense items on it; your template would allow you to spawn another
page with additional expense items.
S. Click the Done button, returning to your PDF document.
‘Turn to page 3 (now apparently page 2) in your Acrobat file and repeat
steps 1 through 5, turning that page into a template. I named this second
template tptAddress, but you may give it any name you choose. As always,
something short and descriptive is best.
The Check Box JavaScript
Having created our templates, we need to add a JavaScript to our check box
that will spawn the templates. We shall attach this JavaScript to the Mouse
Up event for our check box field, chkYes. (Note that this check box is the
only control visible to the user when the form first opens.)
ur JavaScript must carry out two steps for each template we want to spawn:
2. Create a Tenplate object that represents that template.
A Template object is a JavaScript object that represents a particular
template within your JavaScript program. You create Template objects8B EXTENDING ACROBAT FORMS WITH JAVASCRIPT
with a call to the current document's getTenp1ate method. The phrase
this.getTemplate("tptAddress*) creates a Template object represent-
ing the template, tptAddress. (Remember that this in a JavaScript
refers to the current document.)
2. Call the Tenplate object’s spawn method.
The spawn method creates a duplicate of the template’s contents, adding
the contents either to an existing page or to a new page that’s inserted
into the document. (We'll see how to specify exactly where the contents
go ina moment.)
‘Our Mouse Up JavaScript will need to carry out these two steps for each of
the two templates in our form.
To attach the JavaScript to our check box:
Start with the check box’s Field Properties dialog box displaying the
Actions panel, as shown in Figure 9.5. (See Chapter 1 for a reminder of
how to get here.)
2. Select the Mouse Up event and click the Add button.
‘The Add an Action dialog box appears.
Name: [chkves ‘Type [Check Box —¥)
shor Description
Cae)
)
Figure 9.5 Were going to attach our template-spawning
JavaScript to the check box’s Mouse Up event.9 | DYNAMIC CONTROLS WITH TEMPLATES 99
2. In the Add an Action dialog box, select JavaScript in the pop-up menu
and click the Edit button.
Acrobat will present you with the usual JavaScript Edit dialog box.
3. Type the following script into the JavaScript Edit dialog box (Figure 9.6):
var orderInfoTenplate = this.getTenplate(*tptMovielnfo")
var addressTemplate = this.getTemplate("tptAddress")
4
if (this.numPages == 1) {
— orderInfoTemplate.spawn(0, false, true)
— addressTemplate.spawn(1, false, false)
}
4. Exit from all the dialog boxes until you are once again looking at your
Acrobat page.
8. Try it out: With the Hand tool, click the check box; the other form
fields and the second page will all appear.
maser
Use this dialog 1 create and edit your javaSerpt
cece erate = Ths gatTemsletipwoaeTTT
AdoressTerolate = ths puTempiaerpiadarese
(ns eumbages == 1)
‘raernvoTemcite spawn ase. tue)
‘SoressTemetae sewn. faze te)
we. cold
Ge Gm CHD
Figure 9.6 We type our JavaScript into the JavaScript
Edit dialog box.
The code in detail
var orderInfoTemplate = this.getTemplate("tptMovielnfo")
var addressTemplate = this.getTemplate("tptAddress")
These two lines make calls to the getTenplate method, obtaining Tenplate
objects for both of the templates in this form. The first line gets the
tptMovielnfo template (which originally was page 2 in our Acrobat100 EXTENDING ACROBAT FORMS WITH JAVASCRIPT
document) and assigns it to a variable named orderInfoTenplate. The second
line gets our page 3 template and assigns it to the variable addressTenplate.
if (this.numPages == 1) {
This call to the if command receives, in parentheses, a comparison that
checks to see if the current page number is 1. If so, if executes the
JavaScript lines in the braces; these lines spawn our two templates. The
Doc property nunPages is the number of pages in the Acrobat document.
We are doing this test because we want to spawn our templates only once,
when the user first clicks the check box. If the user repeatedly clicks chkYes,
we don't want each Mouse Up to add another set of spawned controls to the
Acrobat document, one on top of another.
Since the tptAddress template will add a new page to our Acrobat form, our
JavaScript can look at the number of pages currently in the form to deter-
mine whether or not we have already spawned the templates. If our docu-
ment has only one page (that is, if this nunPages == 1), then we have not
yet spawned any new pages and we can add the new controls and page to
our document.
orderInfoTemplate.spawn(0, false, true)
Here we spawn our page 2 template, adding that template’s contents to the
current page in our form (Figure 9.7). The Tenplate object’s spawn method
takes three arguments (that is, three values that must be passed in parenthe-
ses when we call the method): a page number and a pair of Boolean values.
Depending on the arguments you give it, spawn duplicates the template’s
contents onto either a currently existing page or a new page in the Acrobat
document.
CONTINENTAL, CONTINENTAL
BiViDe soem BiViDe semen
Yet Send ne my fre ov04 Yet Send nem free ovot
es rere eave depart?
Wh mane wala? Wc nave maya
Wrets yar offer cote? ° Wrers yar otter cate?
= =
Figure 9.7 The template that was originally page 2 in our document is over-
laid onto the first page (in other words, page number 0) of our form.