Ber
Ber

Reputation: 695

Using JavaScript in Adobe Acrobat XI to modify a PDF field value

I have two fields in a PDF I'm editing in Adobe Acrobat XI, "Text2#0" and "Text2#1".

I'm trying to make it so when you enter text into the second field (Text2#1), it shows up in the first field (Text2#0), but enclosed between a pair of asterisks (this is for a barcode generator).

In the 'Text Field Properties' window for Text2#1 on the 'Actions' tab, I set a MouseUp trigger to Run a JavaScript:

var barcodeField = this.getField("Text2#0");
var barcodeLength = barcodeField.length;


if( barcodeField.charAt(0) != "*" ){
  barcodeField = "*" + barcodeField;     
};

if( barcodeField.charAt(barcodeLength - 1) != "*" ){
  barcodeField = barcodeField + "*";
};  

However, the encapsulating asterisks are never added. What am I missing?

Thanks for reading!

EDIT:

Thanks to Max for his answer below. What I did was change the names of the fields as he mentioned (the barcode field was changed to "barcode" and the text field to "Text2"), and then I made a 'On Blur' trigger (when the user stops interacting with the field) associated with Text2. Here is the JS that trigger runs:

getField("barcode").value = getField("Text2").valueAsString;

var barcodeField = this.getField("barcode");
var textField = this.getField("Text2");

barcodeField.value = "*" + textField.value + "*";

Upvotes: 0

Views: 5006

Answers (1)

Max Wyss
Max Wyss

Reputation: 3615

No surprise that the asterisks are not added.

The barcodeField variable is a Field Object, and a Field Object can not add strings.

In order to do something with the content of the field, you would need the value property of the Field Object.

That said, your line would have to look like this:

barcodeField.value = "*" + barcodeField.value ;

However, there is a much more fundamental issue.

The #1 or #2 suffix to the field name is the widget number of the field. In Acrobat JavaScript, the key to the field is its name. When you have multiple fields with the same name, they are differentiated with the widget number.

Some Field Object properties apply to the field (and are the same for all widgets), others apply to the widget (and are different from widget to widget). For example, rect applies to the widget. But value applies to the field, meaning that all fields with that name show the same.

So, if you want to have a field showing the asterisks, and one not showing them, you will have to use two fields, with different field names.

The example could look like this:

var bcf = this.getField("barcodeField") ; // has plain value
var bcfa = this.getField("barcodeFieldA") ; // has value with asterisks

bcfa.value = "*" + bcf.value + "*" ;

If you add this code to the Calculate event of the bcfa field, you would have to change the last line to

event.value = "*" + bcf.value + "*" ;

And that should do it.

Upvotes: 1

Related Questions