Documentation Archive

Developer

Mac Automation Scripting Guide

Prompting for a Choice from a List

Use the Standard Additions scripting addition’s choose from list command to prompt the user to select from a list of strings. Listing 28-1 and Listing 28-2 ask the user to select a favorite fruit, as seen in Figure 28-1.

Figure 28-1Prompting the user to choose from a list of items image: ../Art/choosefromlist_2x.png

APPLESCRIPT

Open in Script Editor

Listing 28-1AppleScript: Prompting the user to choose from a list of items
  1. set theFruitChoices to {"Apple", "Banana", "Orange"}
  2. set theFavoriteFruit to choose from list theFruitChoices with prompt "Select your favorite fruit:" default items {"Apple"}
  3. theFavoriteFruit
  4. --> Result: {"Apple"}

JAVASCRIPT

Open in Script Editor

Listing 28-2JavaScript: Prompting the user to choose from a list of items
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. var fruitChoices = ["Apple", "Banana", "Orange"]
  4. var favoriteFruit = app.chooseFromList(fruitChoices, {
  5. withPrompt: "Select your favorite fruit:",
  6. defaultItems: ["Apple"]
  7. })
  8. favoriteFruit
  9. // Result: ["Apple"]

The choose from list command can optionally let the user choose multiple items by setting the multiple selections allowed parameter to true. For this reason, the result of the command is always a list of selected strings. This list may be empty if the empty selection allowed parameter has been specified and the user dismissed the dialog without making a selection.