Hiding and showing form fields using JavaScript

Learn how to design a form using Acrobat JavaScript to show and hide form fields based on user actions.

By July 7, 2006

 

Scope: Acrobat Professional 6.0 and greater
Skill Level: Beginner
Prerequisites: Familiarity with Acrobat Professional, the JavaScript Console, and the Acrobat JavaScript Reference.

Many forms have optional sections. To keep the user focused on only those parts of the form they need to fill out, and to keep them from being confused, it is often useful to hide some form fields. This tip shows how to design a form using Acrobat JavaScript to show and hide form fields based on user actions.

The Basics of Field Visibility

A form field on a PDF document can be visible in the PDF viewer (i.e. Acrobat, Reader), on the printed document, or both. The Acrobat JavaScript DOM provides three different Field Object properties for controlling these options, listed in the table below.

Field Property

Description

hidden

Deprecated Property – May be removed in future versions of Acrobat

Boolean Value:

  • true – Hides Field in Viewer
  • false – Shows Field in Viewer

print

Deprecated Property – May be removed in future versions of Acrobat

Boolean Value:

  • true – Field Displayed in Printed Document
  • false – Field not Printed

display

Integer Value – Replaced hidden and print in Acrobat version 4.0

  • 0 – Field Visible in Viewer and Printed Document
  • 1 – Field Hidden in Viewer and in Printed Document
  • 2 – Field Visible in Viewer, Hidden on Printed Document
  • 3 – Field Hidden in Viewer, Visible on Printed Document

As noted in the table, the first two properties are deprecated. This means that Adobe re-thought how they had set up these properties and decided to change it. However, lots of documents had already been created using these properties so they left them in the DOM until such time they feel it’s ok to remove them in a future version. These properties are intended to be used only for scripts that will be viewed in the version of Acrobat preceding deprecation, which happens to be version 3.0. Otherwise, stick with the display property. Basically, always use the display property.

Display constants

Acrobat provides a set of constants in the display object so you don’t have to remember which integer value corresponds to which field display option.

Constant Name

Integer Value

Description

display.visible

0

Field Visible in Viewer and Print

display.hidden

1

Field Hidden in Viewer and in Print

display.noPrint

2

Field Visible in Viewer, Hidden on Print

display.noView

3

Field Hidden in Viewer, Visible on Print

Examples

All examples are provided in Sample_ShowHideFields.pdf
Download <?php makeFileTypeLabel("PDF","193 KB"); ?>

Setting Field Visibility based on a Single Check Box Setting

Probably the simplest case for setting field visibility is a single check box. When checked, some other fields are made visible and when unchecked the fields are hidden. In the first example of the sample file a check box is used to display a set of fields for entering additional info. Notice that not only are the entry fields made visible, but visibility of the field labels is also controlled. The field labels are really read-only text fields.

In general, there are two locations where the visibility code can be placed; in the field that triggers the visibility change or the field that receives the visibility change. Which location is best depends on the specific situation. For this sample, multiple fields receive the change, but only a single field (the Check Box) is used as the trigger. The easiest approach is to use the Mouse Up event for the Check Box. This particular event is used because it happens after the value of the Check Box has been updated. The Mouse Down event would not work because it happens before the Check Box value is changed. A segment of the code is shown below.

var nHide = event.target.isBoxChecked(0)?display.visible:display.hidden; 
this.getField("LblShippingInfo").display = nHide; 
this.getField("LblShippingStreet").display = nHide; 
this.getField("ShippingStreet").display = nHide;

The first line determines the visibility by examining the state of the check box with the event.target.isBoxChecked(0) function. The first part of this code, event.target, refers to the target of the event, which is the Check Box. The argument to the function isBoxChecked() is a 0, which refers to the first instance of the checkbox. If there were several Check Boxes with the same name this argument would be used to distinguish between them. The true/false return value of this function is then used to select the visibility state with the Conditional Operator, i.e., the question mark operator. This operator is equivalent to using an if statement. The additional lines of code simply apply the visibility state to the appropriate fields.

Setting Field Visibility based on a Radio Button Setting

One characteristic of Radio Buttons is that the user can only turn a button on. The buttons are turned off automatically when the user makes another selection. This characteristic simplifies the code for showing and hiding fields in Sample #2. In this sample there are two Radio Buttons, one hides the fields and one shows the fields. Since it is a given when the user clicks on a button that button will be selected, there is no need for code to determine the state of the selection. Each button has a script in the Mouse Up event. The script for the Married Radio Button assigns display.visible to each of the fields in the Spouse Information block, and the script for the Single Radio Button assigns display.visible to these same fields.

As well as the fields and field labels, the Spouse Information block includes a gray background that contains and highlights the Spouse Information fields. There are several different ways to create this effect depending on the form developer’s skill level and tools available. For example, it could be an OCG, a Text Field, or a Stamp Annotation. In this example a Square Markup Annotation is used. All annotations have a hidden property that works in exactly the same way as the deprecated hidden property for a field. Using it is simply a matter of being able to acquire the annotation object. The easiest way to do this is to acquire the annotation by name, which is how it is done in the example code with the following line.

this.getAnnot(0,"SpouseInfoBlk").hidden = false;

However, unlike fields, annotations created from the user interface are given very cryptic, auto-generated names. There is no way to access the annotation name from the Acrobat user interface. Giving the annotation a reasonable (human readable) name, has to be done with JavaScript. When this sample was created the background annotation was the only annotation on the PDF, simplifying the situation considerably. Its name was changed by executing the following line of code in the JavaScript Console.

this.getAnnots(0)[0].name = “SpouseInfoBlk”;

The getAnnots() function returns an array of annotation objects for the specified page. Since we know there is only one annotation on the page, the [0] notation is sufficient. If there were more annotations, a little more work is required to identify the correct one.

Setting Field Visibility based on “Radio Check Box” Settings

Check Boxes can be made to act similar to Radio Buttons. This is done by giving a set of Check Boxes the same field name, and giving each a different export value. The difference between this setup and real Radio Buttons is the Check Boxes can be turned off, allowing the user the choice of not selecting any options. With Radio Buttons, once a selection is made it cannot be cleared. We’ll call this merged control a “Radio Check Box”.

Sample #3 uses “Radio Check Boxes” to implement the selection of a title, the advantage being that users do not have to select a title at all if they don’t want to. Selecting the last option, Other, displays a single text field for entering a custom title. Since there are four Check Boxes and the user can turn off this option from any one of them, we might conclude that a script should be placed in the Mouse Up event for each button, but this is inefficient since we’d be repeating the same code for each. Instead, this example uses an event common to all the Check Boxes, the Validate event. This event is called whenever any of the Check Boxes change value. Unfortunately, the script for the Validate event cannot be entered from the Acrobat user interface, it can only be accessed from JavaScript with the field.setAction() function. The code for setting up this Validate event is run from the JavaScript Console. It is available in the sample file and also shown below.

var strJS = 'this.getField("OtherTitle").display =’ +    ‘(event.value == "Other")?display.visible:display.hidden;'; 
this.getField("Title").setAction("Validate",strJS); 

The first two lines of code build a string version of the Validate script. This script is a single line of code. It’s only function is to set the OtherTitle field to visible when the export value from the Check Boxes is “Other”. The third line of code sets Validate event script for the Title field, which is the name given to all of the “Radio Check Boxes”.

Setting Field Visibility based on Valid Form Data

In Sample #4 a Submit Button is made visible only when all required field data is entered. This same technique could also be used to make a Signature field visible. The general idea is that the hidden field represents the last thing the user is supposed to do. The field is hidden until everything is ready. The code for showing the hidden button is more complex than that given in previous examples because it has to check every field on the form. The logical place to put such a script is in a Calculate event since this type of event is triggered anytime a change is made to any field on the form, providing a way to continuously check all the fields. Both the Button and Signature fields have a Calculate event that can be set through JavaScript in the same way the Validate script was set in Sample #3. However, the complexity of a script that checks all the other fields on the document makes this methodology awkward. It is much better to have this script in a location where it can be easily debugged and changed. For this reason, the script is placed in the Calculate event of a special hidden Text field. The Text field was added to the form solely for the purpose of allowing us to use a Calculate event for which we have easy access to script.

The script itself, shown below, is written in an easy to read manor to simplify debugging and future changes.

var bReady = true; 
if(this.getField("FormName").value.length == 0)   bReady = false; 
else if(this.getField("FormAddress").value.length == 0)   bReady = false; 
else if(this.getField("FormEmail").value.length == 0)   bReady = false; 

if(bReady)   this.getField("DoSubmit").display = display.visible; 
else   this.getField("DoSubmit").display = display.hidden;

At the top of the script the bReady variable is defined and defaulted to true. The following code tests each form field to see if data has been entered into it and sets bReady to false only if the test fails. In a real form these tests would most likely be more complex. For example, if the form contains optional or conditional sections, then it might be necessary to first test a Check Box, Radio Button, or other conditions before testing the fields in the section.


Did you know?

  • You can ask a question and get an answer from one of our experts.
  • You can search our database of over 800 tutorials by product and/or topic.
  • You can leave a comment below for the author of this tutorial.

Related topics:

PDF Forms, JavaScript

Top Searches:

Convert existing forms to fillable PDFs, fill and sign any form, Edit PDF, create PDF, Action Wizard

2 comments

Comments for this tutorial are now closed.

Lori Kassuba

12, 2015-09-29 29, 2015

Hi raymundo,

Have you tried looking on the NY state government website?

Thanks,
Lori

raymundo

4, 2015-09-24 24, 2015

Useful commentary - I loved the analysis - Does someone know where my company would be able to get access to a fillable 2015 NY DTF IT-2663 document to work with ?

Thom Parker

2, 2015-04-16 16, 2015

Cesar, 
  The simplest way to force changes in a field from a radio button group, or any group of fields (i.e. multiple fields changing one field) is to use a calculation script in the target field. Please post this question in the forums for more detailed info.

Cesar

12, 2015-04-14 14, 2015

Hello All

let’s say that we have 4 radio buttons on the same Group. Now, i need to know how to do this: when i click on button 1 to display number 1 in a specific field, when i press button 2 to display number 2 in the specific field, and so on for all four buttons. When i click on a button i need to see just the value coresponding to that radio button, and not all of them.

Any help?

Thank you!

Lori Kassuba

5, 2015-03-12 12, 2015

Hi Mike Kimling,

Can you ask your question here and be sure to select the JavaScript category?
https://answers.acrobatusers.com/AskQuestion.aspx

Thanks,
Lori

Mike Kimling

9, 2015-03-09 09, 2015

I am using Adobe Pro XI. My question: In my created PDF, I have ten input fields. If anyone of ten input fields has data typed into them,  I need to enable a column of check boxes on a next page of the PDF or
convert the check boxes to read only when no data is typed in any of the same specific ten input fields.

Eric.

4, 2015-02-23 23, 2015

At the age of 84 I am struggling to understand or to write Javascript for a PDF form, I have got most of it sorted and working but stuck on the following.
I have two check boxes, same name different values, I will call them A & B. They both appear unchecked when the form is opened. Box A is checked to agree a written statement It has no other function.

Box B when checked, unchecks box A

I also want box B when checked to hide an inserted picture and at the same time show six text boxes which are hidden.

I have tried copying and pasting script from various sources and concentrating on the text boxes, including copying script from this tutorial, but nothing works. I might add that the program I am using is PDFill which saves to adobe and the help they give is next to none.  The inserted picture does not have a field name but in it’s properties box there is a provision for linking, action, etc.
Can you make any suggestions please.

Thom Parker

7, 2015-02-04 04, 2015

Kendall, It’s almost exactly the same. Except of course you have to match list selections. Look of articles about lists here on this site.

Kendall

11, 2015-02-04 04, 2015

What about showing/hiding fields based on a dropdown selection? Would that simply be the same as the checkbox selection?

Lori Kassuba

2, 2014-05-28 28, 2014

Hi Michiel,

I’ll let Thom know you found his tutorial helpful. You can also post feature requests here:
https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform

Thanks,
Lori

Michiel

4, 2014-05-28 28, 2014

Why would we need a script for this functionionality….This type of behaviour should just be doable inside the software. It is mind boggling how little is possible within the software itself.

That being said, I appreciate this tutorial. It practically saved my life after almost giving up on Acrobat.

Axel

8, 2014-01-07 07, 2014

Thanks :-)

It works in version XI :-)

Comments for this tutorial are now closed.