JavaScript – Runtime argument lists for popup menus

You’re no doubt familiar by now (if you’ve read enough of my columns) that the Acrobat extensions to JavaScript include a method of the App object called popUpMenu(), which creates a popup-menu list of choices based on the argument list supplied. For a simple list of choices, just supply a list of strings separated by commas:

var reply = app.popUpMenu('Cabernet','Merlot','Pinot Noir');

The reply value will be null if the user let go of the mouse without choosing anything,

or else it will be one of the strings in the argument list, corresponding to the user’s


Sometimes you don’t know in advance what the argument list for popUpMenu() is

going to be, because maybe you need to build the argument list at runtime from data that can

only be had at runtime. The question is, how do you build the argument list for

popUpMenu() dynamically, then execute the call?

You can always build an array at runtime and pass that as the argument to

popUpMenu(), but that’s not exactly what we want. An array is not the same as a list

of strings. An array is an Array object (singular). If you pass an array to a function,

you’ve passed one argument. We want Strings, in a comma-separated list, to use as

arguments (plural) to a function. Be clear on the difference. We don’t want to pass

one argument, but a list of arguments. And we won’t know the number of arguments until

execution time.

Let’s say for sake of example that our arguments are going to consist of the names of all

global variables that currently exist at the time of the menu-pop. We want to determine this

dynamically, and build an argument list accordingly.

Here’s one way to do it:

var args = new String(); // empty stringfor (var i in global) { // enumerate

globals  args += ' ' ' + i + ' ' '; // wrap in quotes  args +=

','; // add comma}args = args.slice(0,-1); // chomp trailing commavar reply =

eval('app.popUpMenu(' + args + ')');

I didn’t say it would be pretty.

The trick should be apparent: We’re building an argument list as one big superstring

(containing lots of single-quote marks!) and embedding that string, in turn, into an

instruction string containing app.popUpMenu( on the front end and ) on the

back end. Then we pass the resulting instruction string to eval(), which makes the

JavaScript interpreter do just-in-time interpretation of it.

So now you know as much as I do about superstring theory.

You May Also Like

About the Author: Kas Thomas

Leave a Reply