Section 4.2. Getting Text Back from Dialog Boxes


4.2. Getting Text Back from Dialog Boxes

So far, all you've done with dialog boxes is display information. That won't help you much if you want to get feedback to use in your scripts, though. Luckily, the display dialog command supports an extra optiondefault answerwhich lets you type text into your dialog boxes as well. Try running this script:

display dialog "Enter your name:" default answer "Sylvester"

A dialog box appears on screen, with a text-entry field inside (Figure 4-1).

Still, even though you can enter text in your dialog boxes with the default answer option, you can't capture the text you entered and reuse it elsewhere in the script.

Or so you might think.

Figure 4-1. The default answer option is all you need to add a text field to a dialog box. Whatever you put in your script after default answer will be what appears in this dialog box at first (top), although you're free to delete the text and enter anything you'd like instead (bottom).


Luckily, using the power of variables, you can store the response to your dialog boxes for later use. Try running this script:

set userResponse to the text returned of (display dialog "Enter your name:" ¬     default answer "Sylvester") display dialog userResponse

The ¬ symbol, shown in the previous example, simply means "this command continues on the next line." This line-continuation symbol has no bearing on how AppleScript interprets your script, so you could theoretically retype the previous script as follows, and it would work exactly the same way:

set ¬ userResponse ¬ to the text returned ¬ of (display dialog ¬ "Enter your name:" ¬ default answer "Sylvester") display dialog userResponse

In this book, scripts employ the line-continuation symbol because certain commands are simply too long to fit within the pages' margins. When entering these commands yourself, you can either type the ¬ symbol as written (by pressing Option-Return) or omit the ¬ symbol altogether and instead just type broken-up commands on a single line.

In this script, AppleScript sets the userResponse variable to the text you enter in the dialog box. Then on the next line, that text is echoed back to you in a new dialog box.



AppleScript. The Missing Manual
AppleScript: The Missing Manual
ISBN: 0596008503
EAN: 2147483647
Year: 2003
Pages: 150

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net