I'm working on a course selection script and each person should only be able to select three courses. I am having issues figuring out how to repeat choose from list if the user selects less than or more than three courses, and only proceed if three choices are selected. Converting the choices from the list to string should work however nothing happens after choosing from list
set theClassList to {"Math ", "English ", "Science ", "I&S ", "Design "}
repeat
set theClass to choose from list theClassList with prompt "Select three courses" with multiple selections allowed
set theClassString to theClass as string
if words in theClassString ≠ 3 then
display dialog "Please select three courses"
exit repeat
else if words in theClassString = 3 then
display dialog "Ok"
end if
end repeat
It's a clever idea to count the words in the theClassString
(which would be done using number of words in theClassString
, instead of simply words in theClassString
). This would work the majority of the time, until a user includes "I&S"
as one of their options, which sadly counts as two words, "I"
and "S"
, since the ampersand is not a word character.
You also had your exit repeat
in the wrong half of the if...then...else
block, since you want to break the loop when the user selects 3 courses, not when they fail to select 3 courses.
Rather than attempting to coerce the result of the list selection into a string, you ought to just count the number of items in the result, which can be done in one of three ways:
count theClass
length of theClass
number in theClass
Here's a reworked version of your script:
property theClassList : {"Math ", "English ", "Science ", "I&S ", "Design "}
property text item delimiters : linefeed
set choices to missing value
repeat
if choices ≠ missing value then display dialog ¬
"You must select precisely three courses"
set choices to choose from list theClassList with prompt ¬
"Select three courses" with multiple selections allowed
if choices = false or the number of choices = 3 then exit repeat
end repeat
if choices = false then return
display dialog choices as text
...And here's a version that uses a recursive handler instead of a repeat loop:
property theClassList : {"Math", "English", "Science", "I&S", "Design"}
property text item delimiters : linefeed
to choose()
tell (choose from list theClassList ¬
with prompt ("Select three courses") ¬
with multiple selections allowed) to ¬
if it = false or its length = 3 then ¬
return it
display dialog "You must select precisely three courses"
choose()
end choose
display alert (choose() as text)