Display Suggestions in a TextField using AS3 and External Files
Tutorial Details
- Difficulty: Beginner
- Program: Flash
- Estimated Completion Time: 1 hour
Suggested Terms is an excellent usability element which helps the user select a better option or just increase search speed.
In this tutorial, we will learn how to create and display suggested terms in a Flash application.
Step 1: Overview
We’ll make use of TextField and String methods and properties to retrieve and display words from an external file containing the search suggestions.
Step 2: Document Settings
Launch Flash and create a new document. Set the stage size to 500x270px, background color to #F6F6F6 and the frame rate to 24fps.

Step 3: Interface

This is the interface we’ll use, a simple background with a title bar and a two TextFields, an Static TextField telling us what to do and an Input TextField that we’ll use to start suggesting.
No buttons this time, the events will be called by pressing a key.
Step 4: Background
You can leave the background color as it is or add 500x270px rectangle to have something you can select. For the title bar, use again the Rectangle Tool (R) to create a 500x30px rectangle and center it.

Step 5: Title
Select the Text Tool (T) and write a title for your application. I used this format: Lucida Grande Regular, 15pt, #EEEEEE.

Step 6: Text Area
We’ll use a Rectangle shape to show where the TextField is.
With the Rectangle Tool, create a 300x24px rectangle and remove the fill, instead, use a #CCCCCC stroke.

Step 7: Input TextField
Lastly, use the Text Tool to create a 345x20px Input TextField and name it inputField.This is the format I used: Helvetica Bold, 16pt, #666666.

Step 8: Font Embedding
To display the font correctly in the Input Text we’ll have to embed it.
Select the Input TextField and go to the Properties panel, Character section and press the Embed… button.
A new window will come up, select the characters you want to embed, and click OK.

Step 9: New ActionScript Class
Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder.

Step 10: Package
The package keyword allows you to organize your code into groups that can be imported by other scripts, its recommended to name them starting with a lowercase letter and use intercaps for subsequent words for example: myClasses. It’s also common to name them using your company’s website: com.mycompany.classesType.myClass.
In this example, we’re using a single class, so there isn’t really a need to create a classes folder.
package
{
Step 11: Import Directive
These are the classes we’ll need to import for our class to work, the import directive makes externally defined classes and packages available to your code.
import flash.display.Sprite; import flash.net.URLLoader; import flash.net.URLRequest; import flash.events.Event; import flash.ui.Keyboard; import flash.events.KeyboardEvent; import flash.text.TextField; import flash.events.MouseEvent; import flash.text.TextFormat;
Step 12: Declare and Extend the Class
Here we declare the class using the class definition keyword followed by the name that we want for the class, remember that you have to save the file using this name.
The extends keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.
public class Main extends Sprite
{
Step 13: Variables
These are the variables we’ll use, read the comments in the code to find out more about them.
private var urlLoader:URLLoader = new URLLoader();//Used to load the external file private var suggestions:Array = new Array();//The suggestions in the text file will be stored here private var suggested:Array = new Array();//The current suggestions private var textfields:Array = new Array();//A textfield to be used to display the suggested term private var format:TextFormat = new TextFormat();//The suggestions text format private var currentSelection:int = -1;//Will handle the selected suggestion in order to write it in the main textfield
Step 14: Constructor
The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object or runs using the Document Class.
public function Main():void
{
Step 15: External File Contents
The terms to suggest will be stored in an external text file, you can also use XML, PHP or the format of your choice.
Write the terms you want to suggest (separated by commas “,” ) and save the file in the same directory as your swf, in this case I used a list of sports and saved them in the file Sports.txt.
Step 16: Load External File
This line calls the load method of the URLLoader class and passes as parameter the url of the txt file we are using.
urlLoader.load(new URLRequest("Sports.txt"));
Step 17: Initial Listeners
Two initial listeners; one listens for the load of the external file and other listens for key up events in the Input TextField.
urlLoader.addEventListener(Event.COMPLETE, loadComplete); inputField.addEventListener(KeyboardEvent.KEY_UP, suggest);
Step 18: Suggestions Text Format
Sets the text format used in the suggestions textfields.
format.font = "Helvetica"; format.size = 12; format.bold = true;
Step 19: Loaded Data
The following function is executed when the external load is complete, it creates an array containing the comma-separated strings in the txt file.
private function loadComplete(e:Event):void
{
suggestions = e.target.data.split(","); //The split method separates the words using as delimiter the ","
}
Step 20: Suggest Function
The suggest function handles all the operations to create and display the suggestions, is executed when the Input TextField detects a Mouse_UP event.
private function suggest(e:KeyboardEvent):void
{
Step 21: Reset
The first thing to do is clear the suggested array, this will erase the previous suggestions (if any).
suggested = [];
Step 22: Search Available Data
The next for loops through the available suggestions and uses an if statement and the indexOf method to search for the starting letters of any of the available words.
for (var j:int = 0; j < suggestions.length; j++)
{
if (suggestions[j].indexOf(inputField.text.toLowerCase()) == 0)//indexOf returns 0 if the letter is found
{
Since all the words in the example text file are in lower case, we can call toLowerCase() on the input text to allow for case-insensitive searching. This means that if the user types “SKI” it will find “skiing”.
Step 23: Create Suggestions TextFields
If the written letter(s) are found, a new TextField is created for the corresponding word, since we are still in the for, if more than one suggestion starts with the same letter(s), then many TextFields will be created.
var term:TextField = new TextField(); term.width = 100; term.height = 20; term.x = 75; term.y = (20 * suggested.length) + 88;//Positions the textfield under the last one term.border = true; /* Here we use the border property term.borderColor = 0x353535; to separate the textfields */ term.background = true; term.backgroundColor = 0x282828; term.textColor = 0xEEEEEE; term.defaultTextFormat = format;//Set the previously created format //Mouse Listeners term.addEventListener(MouseEvent.MOUSE_UP, useWord); term.addEventListener(MouseEvent.MOUSE_OVER, hover); term.addEventListener(MouseEvent.MOUSE_OUT, out); addChild(term); textfields.push(term); //Adds the textfield to the textfields array suggested.push(suggestions[j]); term.text = suggestions[j]; //Sets the found suggestion in the textfield } }
Step 24: Clear TextFields
If the user deletes the letters in the Input Field, the suggestions are removed.
if (inputField.length == 0) //input field is empty
{
suggested = []; //clear arrays
for (var k:int = 0; k < textfields.length; k++)
{
removeChild(textfields[k]); //remove textfields
}
textfields = [];
}
Step 25: Keyboard Control
The next code allows the user to move through the suggestions using the keyboard.
It changes the color of the selected word, adds or removes a number to the currentSelection variable to use it later in the textfields array, this way it retrieves the correct item from the suggestions.
When the enter key is pressed, the selection is written in the Input Field and the suggestions are removed.
if(e.keyCode == Keyboard.DOWN && currentSelection < textfields.length-1)
{
currentSelection++;
textfields[currentSelection].textColor = 0xFFCC00;
}
if(e.keyCode == Keyboard.UP && currentSelection > 0)
{
currentSelection--;
textfields[currentSelection].textColor = 0xFFCC00;
}
if(e.keyCode == Keyboard.ENTER)
{
inputField.text = textfields[currentSelection].text;
suggested = [];
for (var l:int = 0; l < textfields.length; l++)
{
removeChild(textfields[l]);
}
textfields = [];
currentSelection = 0;
}
}
Step 26: Mouse Control
This function is also used to select the suggestion, although this is easier because of the ability to add event listeners to the TextFields. The listeners were added in the suggest()function in Step 23, remember?
private function useWord(e:MouseEvent):void
{
inputField.text = e.target.text;
suggested = [];
for (var i:int = 0; i < textfields.length; i++)
{
removeChild(textfields[i]);
}
textfields = [];
}
private function hover(e:MouseEvent):void
{
e.target.textColor = 0xFFCC00;
}
private function out(e:MouseEvent):void
{
e.target.textColor = 0xEEEEEE;
}
Step 27: Document Class
Go back to the FLA and in the Properties Panel > Publish section > Class field, add Main as value. This will link this class as the Document Class.
Conclusion
You’re done creating and implementing a suggested terms class, it’s time to make your own and customize it! Why not try using PHP to save the terms that users enter to the list of suggested terms?
Thanks for reading this tutorial, I hope you’ve found it useful!


Nice!
i like this
Very useful work, Thanks a lot! I found out a bug though ;)
If you write Capital letter it doesn’t recognize the suggestion.
I mean if I type “a” it will show suggestions but if I type “A” it will not ;)
Thanks again for sharing!
With Regards,
Sagar S. Ranpise
@Sagar: Good point! I’ve made a quick fix to the tutorial to allow the suggestions to be case-insensitive by converting the input term to lowercase.
This will work for the example text file, because all the sports are in lowercase. However, it won’t work for cases where the text file contains capitals — a list of names, for example.
How would you suggest solving this?
Couldn’t you just apply toLowerCase() to the suggestions array? That way you’d definitely be comparing two lowercase strings…
Good call, Barry. Trouble with that is, it means all the pop-up text suggestions will be in lowercase, too. That’s not a problem for this example, but if we had, say, a list of names, displaying them in lowercase would look odd.
Anbody have any ideas for getting around this?
I found something that works. Replace this original “if” statement with this…
<pre name="code"class="html"if (suggestions[j].indexOf(inputField.text.toLowerCase()) == 0 || suggestions[j].indexOf(inputField.text.toUpperCase()) == 0)
Now it should recognize lower and upper case text, whether it’s entered in the input field or in the text file. Also, if you want to continuously scroll through the suggested text boxes replace the Keyboard.DOWN and Keyboard.UP statements with this…
<pre name="code"class="html" if(e.keyCode == Keyboard.DOWN){
if( currentSelection = textFields.length – 1){
currentSelection = 0;
textFields[currentSelection].textColor = 0xFFCC00;
}
}
if(e.keyCode == Keyboard.UP){
if(currentSelection > 0){
currentSelection –;
textFields[currentSelection].textColor = 0xFFCC00;
}
else if(currentSelection <= 0){
currentSelection = textFields.length – 1;
textFields[currentSelection].textColor = 0xFFCC00;
}
}
Nice one Stu :) But what if I typed in, say, “Ski” for example?
Neat modification for the looping text selection, too!
Hmmmmmmm, I like. There is so much one can do with this. Can take it real far! NICE!
excellent tutorial , i want to change inputfield to tlf text what i change to work with other language
Great work, how would I make sure that the suggestion text fields are removed if someone is typing something not in the list, or am I missing that in the source code?
This tool is GREAT, I am trying to get it implemented into my site now. Is there anyway it can give you a error if that name is not in your text file?
Like “Name not found” or something?
I tried:
if(inputField.text != suggested.text) { //and that did not work
if(inputField.text != suggestions.text) { //and that did not work
I was ust going to disable the button, but I couldn’t figure it out. Did anyone else have any luck?
Maybe with this:
for (var j:int = 0; j < suggestions.length; j++)
{
if (inputField.text != suggestions[j]){
}
}
// This way it will compare the text that has been typed, with all the available text in the text file.
Thanks for the source code. I’ll definitely try this out
Definitely will use this in some of my projects. Nice work!
Nice code! I dealt with the case sensativity by using a Regular Expression and string.search.
ie:
var pattern:RegExp = new RegExp(inputBox.text,”i”); // SEARCH TERM
var cnt:int = 0;
// use text in inputBox to build array of relevant suggestions
if (inputBox.text != “”) { // if blank, don’t suggest anything!
for (i = 0; i < cachedResults.length; i++) { // iterate through cached result set
if (cachedResults[i].search(pattern) > -1 ) { // if pattern exists in string…
suggestion[cnt] = cachedResults[i]; // place in suggestions array
cnt++
}
}
}
TypeError: Error #1010: A term is undefined and has no properties.
at try_fla::MainTimeline/suggest()
This Error is removed when the following lines of code are commented out:
if (suggestions[j].indexOf(inputField.text.toLowerCase()) == 0)
help required urgently.
Use Ctrl-Shift-Enter (instead of Ctrl-Enter) to run the SWF, and it’ll tell you which line that error is occurring on, and possibly which exact term is causing the problem.
Great !!! Thanks a lot for sharing the awesome tutorial.
Un saludo Michael Williams
Disculpa que te moleste, tengo una consulta, como puedo añadir un botón en el documento, ejemplo, un botón de una “ñ” y al darle clic al botón automáticamente me cargue el símbolo de la “ñ” en el textfield, por favor agradecería un montón tu ayuda, desde ya gracias por compartir
‘Sorry to bother you, I have a question, as I can add a button in the document, such as a button “ñ” and click the button to automatically give me load the symbol of the “ñ” in the textfield, please welcome a lot your help, of course thanks for sharing’
Yeah, that should be possible. You can use the caretIndex property of the TextField to get the position of the cursor, and then insert the symbol with a little String manipulation :)
Awesome tut. thanks a lot.
Hi! Very helpful tutorial. Thanks a lot. Could you please tell me how can I restrict the number of textFields shown in clip? If it’s possible, what should I do to get scrolling?