Quick AppleScript question - Set variable depending on if [ok] or [cancel] pressed

Discussion in 'Mac Programming' started by maclover001, Jan 16, 2009.

  1. maclover001 macrumors 6502a

    maclover001

    Joined:
    Mar 25, 2008
    Location:
    Vancouver, Canada
    #1
    Hey,

    I'm trying to make a two-button dialog box, if one button is pressed, it sets a variable to [1], if the other button is pressed, it sets the variable to [2]

    This is my code:

    Code:
    display dialog "Hello world"
    set var1 to 1
    
    if var1 is 1 then display dialog "The variable is set to one"
    if var1 is 2 then display dialog "The variable is set to two"
    With this method, clicking [ok] sets the variable to [1], but how can I get it so clicking [cancel] sets it to [2]? Or even better, rename the two buttons?

    Thanks
     
  2. HexMonkey Administrator

    HexMonkey

    Staff Member

    Joined:
    Feb 5, 2004
    Location:
    New Zealand
    #2
    You can specify the button names and default button as follows:

    Code:
    display dialog "Hello world" buttons {"Button 1", "Button 2"} default button "Button 2"
    To find out which button was pressed, you need to access the button returned property of the dialog. You can do this as follows:
    Code:
    display dialog "Hello world" buttons {"Button 1", "Button 2"} default button "Button 2"
    set theButton to button returned of the result
    Or just:
    Code:
    set theButton to button returned of (display dialog "Hello world" buttons {"Button 1", "Button 2"} default button "Button 2")
    You can then compare theButton to the button names to check which button was pressed (eg 'if theButton is "Button 1" then...').
     
  3. maclover001 thread starter macrumors 6502a

    maclover001

    Joined:
    Mar 25, 2008
    Location:
    Vancouver, Canada
    #3
    Thanks :)
     

Share This Page