Search code examples
macosapplescript-objc

How to make dialogue box in apple script to wait until user gives in put


I am trying to get a dialogue box in mac using apple script.

    tell application "System Events"
    activate
    display dialog "Enter your name:  " default answer "" buttons {"OK"}   default button "OK" with title "Good Name"
    set the Name to text returned of the result

The problem i am facing is, when i don't enter name, the popup is closing by itself throwing error. But i want it to stay alive till user gives input


Solution

  • You'll want to add a repeat that which acts on the error:

    set theMessage to ""
    set theIcon to note
    
    tell application "System Events"
        activate
        repeat
            display dialog theMessage & "Enter your name:  " default answer "" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" with title "Good Name" with icon theIcon
            set the theName to text returned of the result
            try
                if theName = "" then error
                exit repeat
            on error
                set theMessage to "Invalid. "
                set theIcon to caution
            end try
        end repeat
        display dialog "Your name is " & theName & "." buttons {"OK"} default button "OK" with icon note
    end tell
    

    When input is "" within the repeat on error is triggered, which gives an invalid message and repeats the input dialog — otherwise the script continues (name output added as example).