JavaScript Examples

These examples illustrate the properties and methods that are supported in this scripting environment.

Referencing objects

These examples illustrate several ways to reference an object.

When accessing a specific instance of an object, be aware of the occurrence number of the object where the script resides. The script will return the object with the same occurrence number as the object where the script resides. For example, there are three buttons with the same name (Button1[0], Button1[1] and Button1[2]) and three text fields with the same name (TF1[0], TF1[1] and TF1[2]). If the script on Button1[2] is xfa.host.messageBox(TF1.rawValue) , the result will be TF1[2].rawValue , and not TF1[0].rawValue .

Scripts

Accessing the first instance of a text field

// Access a sibling field using the field name. 
// Access the first instance of TextField1.  
TextField1.rawValue = "Hello";

Accessing the first instance of a text field

// Access the first instance of TextField1. When scripting with JavaScript, use 
// xfa.resolveNode to start the search at the top and move down the form  
// hierarchy. 
xfa.resolveNode("TextField1").rawValue = "Hello"; 
xfa.resolveNode("TextField1[0]").rawValue = "Hello";

Accessing a field with accessors

// When scripting with JavaScript, use the resolveNode() method to access a 
// field with a SOM expression that contains a # or [] operator. When searching 
// with this.resolveNode, the search starts at the current object and moves up 
// the form hierarchy.  
this.resolveNode("Subform2[1].NumericField4").rawValue = 25;

Accessing a subform with an index number

// Access a subform with an index number. When using xfa.resolveNode,the search 
// starts at the top of the form hierarchy and moves down.  
var nIndex = 2; 
var sSOM = "Subform2[" + nIndex + "]"; 
var oSubform = xfa.resolveNode(sSOM); 
oSubform.NumericField4.rawValue = "25";

Accessing a field property

// Access a field property using a property name and value. 
// Change the field properties of a specific subform. 
// Use the [] operator to access an object's property. 
var sProperty = "access"; 
var sValue = "readOnly"; 
 
// First, get the subform nodes. 
    var oNodes = Subform2.nodes; 
    var nNodesLength = oNodes.length; 
 
    // Loop through the subform's nodes and look for fields. 
    for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount ++) { 
        // Set the field property. 
        if (oNodes.item(nNodeCount).className == "field") { 
            oNodes.item(nNodeCount)[sProperty] = sValue; 
        } 
    }

Counting the text fields in a document

// Count the number of text fields in a document.  
// Get the field containers from each page. 
for (var nPageCount = 0; nPageCount < xfa.host.numPages; nPageCount++) { 
 
    var oFields = xfa.layout.pageContent(nPageCount, "field"); 
    var nNodesLength = oFields.length; 
    var nCount = 0; 
 
    for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) { 
 
        if (oFields.item(nNodeCount).ui.oneOfChild.className == "textEdit") { 
            nCount++; 
        } 
    } 
    TextField1.rawValue = nCount; 
}

Accessing fields using partial object names

// Access fields using partial object names. 
// Get the field containers from each page. 
for (var nPageCount = 0; nPageCount < xfa.host.numPages; nPageCount++) { 
 
    var oFields = xfa.layout.pageContent(nPageCount, "field"); 
    var nNodesLength = oFields.length; 
 
    for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) { 
        if (oFields.item(nNodeCount).name.substr(0,2) == "Te") { 
            xfa.host.messageBox(oFields.item(nNodeCount).name); 
        } 
    } 
}

Accessing a choice list value

// Use the newText or prevText property to access the choice list value before 
// or after the value changed. 
// Trigger the script on a change event. 
TextField1.rawValue = xfa.event.prevText; 
TextField2.rawValue = xfa.event.newText;

Accessing a field in a subform

// Access a field nested inside a sibling subform by prefixing the field name 
// with its parent name. 
Subform2.TextField3.rawValue = "Hello";

Accessing fields in a subform

// Access the first-level fields nested inside a subform. 
Subform1.resoveNodes("#field[*]")

Getting the fields from each page

// Get the field containers from each page. 
for (var i = 0; i < xfa.host.numPages; i++) { 
 
var oFields = xfa.layout.pageContent(i, "field"); 
var nodesLength = oFields.length; 
 
// Set the access type. 
for (var j = 0; j < nodesLength; j++) { 
 
        var oItem = oFields.item(j); 
 
        if (oItem != this) { 
 
        oItem.access = "readOnly"; 
        } 
    } 
}

Creating a node in the data model

This example illustrates how to create or clone a new data model node.

Script

Creating a data node

// Display the number of child nodes under the rootNode (xfa.record). 
// rootNode is the data file's root node. 
xfa.host.messageBox("Initial number of nodes under rootNode: " + xfa.record.nodes.length); 
// Create a node of type dataGroup. 
var oGroupNode = xfa.datasets.createNode("dataGroup", "NewGroupNode"); 
 
// Append the data group node to an existing data model node. 
xfa.record.nodes.append(oGroupNode); 
 
// Display the number of child nodes under rootNode. 
xfa.host.messageBox("Number of nodes under rootNode after first append: " + xfa.record.nodes.length); 
 
// Create a node of type dataValue. 
var oValueNode = xfa.datasets.createNode("dataValue", "NewValueNode"); 
 
// Set the value of the new data value node. 
oValueNode.value = "The item value"; 
 
// Append the data value node to the data group created above. 
xfa.record.NewGroupNode.nodes.append(oValueNode); 
 
// Get the value from the data model. 
TextField1.rawValue = xfa.record.NewGroupNode.NewValueNode.value; 
 
// Append a cloned data group node. 
xfa.record.nodes.append(xfa.record.NewGroupNode.clone(1)); 
 
// Display the number of child nodes under rootNode. 
xfa.host.messageBox("Number of nodes under rootNode after appending clone: " + xfa.record.nodes.length); 
 
// Set the value of the new data value node. 
xfa.resolveNode("xfa.record.NewGroupNode[1].NewValueNode").value = "The clone value"; 
 
// Get the value of the cloned data value node. 
TextField2.rawValue = xfa.resolveNode("xfa.record.NewGroupNode[1].NewValueNode").value; 
 
// Remove the cloned data group from the node list. 
var oRemoveNode = xfa.resolveNode("xfa.record.NewGroupNode[1]"); 
xfa.record.nodes.remove(oRemoveNode); 
 
// Display the number of child nodes under rootNode. 
xfa.host.messageBox("Number of nodes under rootNode once clone node removed: " + xfa.record.nodes.length);

Manipulating instances of a subform

These examples illustrate several ways to add or remove instances of a subform at run time.

Use the instance manager to manipulate the pages of a form that has a fixed layout. Each page is a subform; therefore, adding or removing a subform will look like adding or removing a page. However, at run time, you cannot change the layout of a form that has a fixed layout. You can add and delete instances at the form:ready event; however, if the script is on a run-time event, such as click , nothing will happen.

Scripts

Adding an instance by invoking the instance manager

// Add an instance of a subform by using the underscore syntax to invoke the 
// instance manager directly. 
// Forms rendered in a web browser do not support the underscore syntax. 
// However, the underscore syntax is supported if the script runs at the 
// server. 
_Subform2.addInstance(1);

Adding an instance by invoking the instanceManager property

// Add an instance of a subform by invoking the instanceManager property. Be 
// careful to ensure that adding a subform will not violate the max occur 
// value. 
Subform2.instanceManager.addInstance(1);

Removing an instance

// Remove an instance of a subform. Set the min occur value only if removing an 
// instance will violate it. For example, set the min occur to 0 if you want to 
// remove the last, or the only, instance of a subform.  
// Forms rendered in a web browser do not support the underscore syntax. 
// However, the underscore syntax is supported if the script runs at the 
// server.  
Subform2.occur.min = "0"; 
_Subform2.removeInstance(0);

Removing the parent subform

// Remove the parent subform. 
parent.occur.min = "0"; 
parent.instanceManager.removeInstance(parent.index);

Setting the number of instances

// Set the number of instances of a subform. 
var oSubform = xfa.resolveNode("Subform2"); 
oSubform.instanceManager.setInstances(5);

Inserting a new subform instance

// Insert a new subform instance. This script will not work with a static form. 
// The script is invoked by a button, named Insert Subform, that is nested 
// inside a repeating subform. The new subform is inserted below the current 
// subform.  
var oSubform = this.resolveNode("Subform2"); 
var oNewInstance = oSubform.instanceManager.addInstance(1); 
var nIndexFrom = oNewInstance.index; 
var nIndexTo = this.parent.index + 1; 
// Invoke the instanceManager to insert the subform below the current one. 
oSubform.instanceManager.moveInstance(nIndexFrom, nIndexTo);

Adding and removing a subform

// Invoke the instance manager to add and remove the comments subform. 
if (fComments.value == "0") { 
// In this example, fComments is a document variable used as a flag. 
// The fComments variable equals 1 when the comments subform is displayed. 
_comments.setInstance(1);  
// Add the comments subform. Change the button's caption. 
this.resolveNode("caption.value.#text").value = "Clear Comments";  
// Set the flag value. 
fComments.value = "1";  
} 
else { 
// Remove the comments subform. 
_comments.setInstance(0);  
// Change the button's caption. 
this.resolveNode("caption.value.#text").value = "Add Comments";  
// Reset the flag value. 
fComments.value = "0"; 
}

Getting or setting object values

These examples illustrate several ways to get or set a value for an object.

Scripts

Using rawValue

// Use the rawValue property to set and get a field's raw value. 
TextField1.rawValue = "K1V1W3"; // Set the field's raw value. 
TextField2.rawValue = TextField1.rawValue // Get the field's raw value. 

Using value

// Use the value property to set and get the field's raw value. 
TextField1.rawValue = "k1V1W3"; 
TextField2.rawValue = TextField1.value.oneOfChild.value

Using formattedValue

// Use the formattedValue property to set and get the field's formatted value. 
// Use the value property to set and get an object's value (picture). 
TextField1.rawValue = "K1V1W3"; // Set the field's raw value. 
TextField1.format.picture.value = "A9A 9A9"; // Set the field's display picture format. 
TextField2.rawValue = TextField1.formattedValue; // Get the field's formatted value. 

Setting a data object’s value

// Use the value property to set and get a data object's value. 
// In this script, groupNode is a data group and addressL1 is a data value in 
// the data file. 
TextField1.rawValue = xfa.record.groupNode.address.line1.value;

Setting the document variable’s value

// Use the value property to set and get the document variable's value. 
TextField1.rawValue = docVar.value;

Working with page numbers and page counts

These examples illustrate several ways to use the host and layout models to work with page numbers and page counts.

The host and layout models have several different properties and methods for working with page numbers and page counts. The properties and methods that you should use depend on what the script does and when it executes.

Many of the host properties and methods are unavailable on the server. Use the host properties and methods to set or get page numbers at run time.

None of the layout methods set the page number. Use the layout methods to get the current page at layout:ready or to display the page numbers at the bottom of the page and see the page number when you open a form on a client.

Scripts

Getting the page number

// Use the page layout methods to get the current page number. 
TextField1.rawValue = xfa.layout.page(this); // 1-based. 
TextField2.rawValue = xfa.layout.absPage(this); // 0-based. 

Getting the page count using the pageCount method

// Use the layout pageCount methods to get the number of pages in a document. 
TextField1.rawValue = xfa.layout.pageCount(); // Get the logical number of pages. 
TextField2.rawValue = xfa.layout.absPageCount(); // Get the physical number of pages. 

Formatting the pagination

// Use the layout page and pageCount methods to format the pagination. 
TextField1.rawValue = "Page " + xfa.layout.page(this) + " of " + xfa.layout.pageCount();

Getting and setting the current page number

// Use the host currentPage property to get and set the current page number at // run time. 
// This script cannot be used during a layout:ready, form:ready, or initialize // event. However, it will work if the script is on a button. 
xfa.host.currentPage = 1; // Go to page 2 (0-based). 

Getting the page count using the numPages property

// Use the host numPages property to get the number of pages in a document. 
TextField1.rawValue = xfa.host.numPages; // Get the number of pages. 

Navigating down a document

// Use the host pageDown() method to navigate through a document. 
xfa.host.pageDown(); // Go to the next page. 

Navigating up a document

// Use the host pageUp() method to navigate through a document. 
xfa.host.pageUp(); // Go to the previous page. 

Concatenating data values

This example illustrates how to concatenate data values into an address block and ensure that there are no blank lines.

Script

Concatenating data values

// Get the values from the data model. 
var sName = xfa.record.groupNode.address.line1.value; 
var sPostbox = xfa.record.groupNode.address.line2.value; 
var sStreet = xfa.record.groupNode.address.line3.value; 
var sCity = xfa.record.groupNode.address.line4.value; 
var sRegion = xfa.record.groupNode.address.line5.value; 
var sCountry = xfa.record.groupNode.address.line6.value; 
var sPostcode = xfa.record.groupNode.address.line7.value; 
var addressArray = new Array(sName,sPostbox,sStreet,sCity,sRegion,sCountry,sPostcode); 
 
var sAddressBlock = ""; 
 
// Don't display the postbox if the value is not provided. 
if (addressArray[1] == null) { 
        sAddressBlock = addressArray[0] + "\n" + addressArray[2] + "\n" + addressArray[3] + "\n"; 
} else { 
        sAddressBlock = addressArray[0] + "\n" + addressArray[1] + "\n" + addressArray[3] + "\n"; 
} 
 
// Do not display the region if the value is not provided.  
if (addressArray[4] == null) { 
sAddressBlock = sAddressBlock + addressArray[5] + " " + addressArray[6]; 
} else { 
sAddressBlock = sAddressBlock + addressArray[4] + ", " + addressArray[5] + " " + addressArray[6]; 
} 
TextField2.rawValue = sAddressBlock; 
// Make sure the field is set to display a multiple line value. To set the 
// multiLine property programmatically, add the following line: 
        TextField2.ui.oneOfChild.multiLine = "1";

Calculating totals

This example illustrates how to calculate totals.

Script

Calculating totals

// Access a field in a repeating subform by looping through the node list. 
var oFields = xfa.resolveNodes("Subform2[*].NumericField4"); 
var nNodesLength = oFields.length; 
var nSum = 0; 
for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) { 
    nSum += oFields.item(nNodeCount).rawValue; 
} 
TextField1.rawValue = nSum;

Changing the background color

These examples illustrate how to change the background color of a subform or fields.

In a form that has a flowable layout, you can change the background color of the entire field, including the caption and the field area, at run time. However, in a form that has a fixed layout, you can only change the background color of the field area at run time.

Scripts

Changing the background color of a subform

// Alternate the background color of a repeating subform. 
var oNodes = xfa.resolveNodes("Subform2[*]"); 
var nNodesLength = oNodes.length; 
 
for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) { 
    if (oNodes.item(nNodeCount).index%2 != 0) { 
        oNodes.item(nNodeCount).border.fill.color.value = "200,200,250"; 
    } else { 
        oNodes.item(nNodeCount).border.fill.color.value = "200,150,250"; 
    } 
}

Changing the background color of a field

// Alternate the background color of the NumericField4 field. 
// Before running this script, set a background color or set the 
// border.fill.presence property to visible. 
var oNodes = xfa.resolveNodes("Subform2[*]"); 
var nNodesLength = oNodes.length; 
var sFillColor; 
 
for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) { 
 
    if (oNodes.item(nNodeCount).index%2 != 0) { 
        sFillColor = "200,200,250"; 
 
    } else { 
        sFillColor = "200,150,250"; 
 
    } 
    oNodes.item(nNodeCount).NumericField4.fillColor = sFillColor; 
}

Changing the background color of rows in a subform

// Reset the fields of the current subform. 
var dString = "xfa.form.form1.dtls[" + this.parent.index + "]"; 
var oDetails = xfa.form.resolveNode(dString); 
var sDtlFields; 
 
// Build the string of field names to reset. 
for (var i = 0; i < oDetails.nodes.length; i++) { 
    sDtlFields = sDtlFields + "," + dString + "." + oDetails.nodes.item(i).name; 
} 
// Pass the string variable as a parameter. 
xfa.host.resetData(sDtlFields); OR  
// Alternate the background color of the repeating rows. 
if (this.index%2 != 0)  this.border.fill.color.value = "255,255,255"; else  this.border.fill.color.value = "201,201,146";

Populating a drop-down list

These examples illustrate several ways to add or remove list items in a drop-down list.

Save the item list before you populate a drop-down list at run time; otherwise, the items will be lost. Only the value is saved in the data.

Scripts

Populating a drop-down list from a web service

// Populate the drop-down list with values from a web service. 
// The web service used in this example is fictional.  
SOAP.wireDump = false; 
var oListURL = "http://www.webservice.net/wsdl/query.wsdl"; 
var e; 
try 
{ 
    xfa.host.messageBox("Starting list retrieval."); 
     
    var service = SOAP.connect(oListURL); 
 
    if(typeof service != "object") { 
        xfa.host.messageBox("Couldn't get List object."); 
    } 
    if(service.getAllServiceNames == "undefined") { 
        xfa.host.messageBox("Couldn't get getAllServiceNames Call."); 
        } 
     
    // Start the query 
    var oItems = service.getAllServiceNames(); 
    if(oItems == null) { 
        xfa.host.messageBox("List empty."); 
        } 
var nCount = 0; 
    var nLimit = 10; 
     
    for(var nItemCount in oItems)  
    { 
        for(var nItemNode in oItems[nItemCount]) 
        { 
            if (nItemNode == "name") 
                DropDownList1.addItem(oItems[nItemCount][nItemNode]); 
        } 
        if (++nCount >= nLimit) 
            break; 
    } 
} 
catch(e) 
{ 
    xfa.host.messageBox("Problem with list Call: " + e); 
}

Clearing a drop-down list

// Clear the items in a drop-down list. 
DropDownList1.clearItems();

Populating a drop-down list from a data file

// Populate the drop-down list with values from a data file. 
var oItems = xfa.resolveNode("xfa.record.groupNode.list"); 
var nItemsLength = oItems.nodes.length; 
 
for (var nItemCount = 0; nItemCount < nItemsLength; nItemCount++) { 
    DropDownList1.addItem(oItems.nodes.item(nItemCount).value); 
} 
DropDownList1.rawValue = "Second item in list";

Saving the values from a drop-down list in another field

// Access the items in a drop-down list box and save their values in a separate 
// field. 
var oItems = xfa.resolveNode("DropDownList1.#items"); 
var nItemsLength = oItems.nodes.length; 
 
for (nItemCount = 0; nItemCount < nItemsLength; nItemCount++){ 
 
    if (TextField2.rawValue == null) { 
        TextField2.rawValue = oItems.nodes.item(nItemCount).value; 
    } else { 
        TextField2.rawValue = TextField2.rawValue + "\n" + oItems.nodes.item(nItemCount).value; 
    } 
}

Accessing a drop-down list value using newText or prevText properties

// Use the newText or prevText properties to access a drop-down list value 
// before or after the value changes. 
// Execute the script on a change event. 
TextField1.rawValue = xfa.event.prevText; 
TextField2.rawValue = xfa.event.newText;

Saving a form

These examples illustrate how to export data from a form and save a form.

Uses

Properties

Methods

target

exportData

Scripts

Exporting form data without specifying a file name

// Export a form's data without specifying a file name. The end user is 
// prompted to provide the file name. 
xfa.host.exportData();      // Will generate data in XDP format. 
xfa.host.exportData("", 0); // Will generate data in XML format. 

Exporting form data using a filename

// If you specify a file name, the script must run on a certified form. 
xfa.host.exportData("filename.xdp");    // Will generate data in XDP format. 
xfa.host.exportData("filename.xml", 0); // Will generate data in XML format. 

Saving a form

// Saving the form is done at the application level, so you need to invoke the 
// Acrobat app model. 
App.executeMenuItem("SaveAs"); // The end user will be prompted to specify a 
// file name.  
// However, you must save the form silently if the form needs to be certified 
// and the certificate must be trusted for privileged JavaScript. 
var mydoc = event.target; 
mydoc.saveAs();

Making an object visible or invisible

This example illustrates how to make an object visible or invisible. If a print button is invisible, it will prevent the user from printing a form.

The prePrint event triggers immediately before the form is rendered for printing. Similarly, the postPrint event triggers immediately after the form has been printed.

Uses

Scripts

Setting a field to be visible or invisible

// If a field is visible, make it invisible and vice versa. 
if(Field1.presence == "visible") 
{ 
    Field1.presence = "invisible"; 
} 
else 
{ 
    Field1.presence = "visible"; 
}

Setting a button to be visible but non-printing

// Set a button to be visible but non-printing at design time.  
Button1.relevant="-print"

Using radio buttons and check boxes

These examples illustrate how to select and clear radio buttons and check boxes.

Scripts

Selecting a radio button

// Select the first radio button. 
RadioButtonList.rawValue = '1'; 
xfa.host.messageBox('Value of RadioButtonList: ' + RadioButtonList.rawValue); 
 
// Select the second radio button. 
RadioButtonList.rawValue = '2'; 
xfa.host.messageBox('Value of RadioButtonList: ' + RadioButtonList.rawValue);

Accessing radio buttons

// Access the radio buttons. 
RadioButtonList.resolveNodes("#field[*]")

Clearing a radio button

// Clear a RadioButtonList value. Any invalid value will clear the list. 
RadioButtonList.rawValue = '3'; 
xfa.host.messageBox('Value of RadioButtonList: ' + RadioButtonList.rawValue);

Selecting a check box

// Select a check box. 
CheckBox1.rawValue = 1; 
xfa.host.messageBox('Value of checkbox: ' + CheckBox1.rawValue);

Deselecting a check box

// Deselect a check box. 
CheckBox1.rawValue = 0; 
xfa.host.messageBox('Value of checkbox: ' + CheckBox1.rawValue);

Determining that a form has changed

This example illustrates how to determine that a form has changed.

Script

Determining that a form has changed

// Save a copy of the original XML file. 
var sOriginalXML = xfa.data.saveXML(); 
 
// Change the form data. 
TextField1.rawValue = "changed"; 
 
// Determine whether the form data has changed. 
if(sOriginalXML == xfa.data.saveXML()) 
{ 
    xfa.host.messageBox("Form has not changed."); 
} 
else 
{ 
        xfa.host.messageBox("Form has changed."); 
}

Disabling all form fields

This example illustrates how to disable all the fields on a form.

Script

Disabling all form fields

// Get the field containers from each page. 
for (var nPageCount = 0; nPageCount < xfa.host.numPages; nPageCount++) { 
var oFields = xfa.layout.pageContent(nPageCount, "field"); 
var nNodesLength = oFields.length; 
 
// Set the field property. 
for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) { 
oFields.item(nNodeCount).access = "readOnly"; 
} 
}

// Ethnio survey code removed