Skip to main content
Participant
May 12, 2025
Answered

JavaScript Formula Help - Merging Fields

  • May 12, 2025
  • 4 replies
  • 673 views

I would like Text1 to read:

NAME

ADDRESS

CITY, STATE, ZIP

 

 

 

var fields = ["NAME", "ADDRESS", "CITY", "STATE", "ZIP"];
var values = [];
for (var i in fields) {
var f = this.getField(fields[i]);
if (f.valueAsString!="") values.push(f.valueAsString);
}
event.value = values.join("\n");

 

Correct answer Thom Parker

Then the fields values need to be joined differently. 

For example:

var fields = ["NAME", "ADDRESS", "CITY", "STATE", "ZIP"];
var aFldVals = fields.map(cNm=>this.getField(cNm).value);
event.value = aFldVals[0] + "\n" + aFldVals[1] + "\n" + aFldVals[2] + ", " + aFldVals[3] + ", " + aFldVals[4]; 

 

4 replies

Participant
May 13, 2025

Text1 is showing:

NAME

ADDRESS

CITY

STATE

ZIP

 

But I would like the City, State, & Zip to be on the same line instead of stacked. 

 

Thom Parker
Community Expert
Thom ParkerCommunity ExpertCorrect answer
Community Expert
May 13, 2025

Then the fields values need to be joined differently. 

For example:

var fields = ["NAME", "ADDRESS", "CITY", "STATE", "ZIP"];
var aFldVals = fields.map(cNm=>this.getField(cNm).value);
event.value = aFldVals[0] + "\n" + aFldVals[1] + "\n" + aFldVals[2] + ", " + aFldVals[3] + ", " + aFldVals[4]; 

 

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Participant
May 13, 2025

That worked! Thank you!!

Thom Parker
Community Expert
Community Expert
May 12, 2025

Here is another way to write the code:

var fields = ["NAME", "ADDRESS", "CITY", "STATE", "ZIP"];
event.value = fields.map(cNm=>this.getField(cNm).value).join("\n");

 

 

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Thom Parker
Community Expert
Community Expert
May 12, 2025

Is your code a calculation script on the "Text1" field?  If it is, then this is the correct way to do it. 

 

Did you check the console window for errors?  If you had you would probably see a type error being reported. This is because of the incorrect usage of the "for/in" loop. Use a regular for loop and it'll work. 

 

 

 

 

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Bernd Alheit
Community Expert
Community Expert
May 12, 2025

Have you a question?