Advertisement
  1. Code
  2. JavaScript

Display Suggestions in a TextField using AS3 and External Files

Scroll to top
7 min read

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.

1
2
package
3
{

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.

1
2
import flash.display.Sprite;
3
import flash.net.URLLoader;
4
import flash.net.URLRequest;
5
import flash.events.Event;
6
import flash.ui.Keyboard;
7
import flash.events.KeyboardEvent;
8
import flash.text.TextField;
9
import flash.events.MouseEvent;
10
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.

1
2
public class Main extends Sprite
3
{

Step 13: Variables

These are the variables we'll use, read the comments in the code to find out more about them.

1
2
private var urlLoader:URLLoader = new URLLoader();//Used to load the external file

3
private var suggestions:Array = new Array();//The suggestions in the text file will be stored here

4
private var suggested:Array = new Array();//The current suggestions

5
private var textfields:Array = new Array();//A textfield to be used to display the suggested term

6
private var format:TextFormat = new TextFormat();//The suggestions text format

7
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.

1
2
public function Main():void
3
{

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.

1
2
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.

1
2
urlLoader.addEventListener(Event.COMPLETE, loadComplete);
3
inputField.addEventListener(KeyboardEvent.KEY_UP, suggest);

Step 18: Suggestions Text Format

Sets the text format used in the suggestions textfields.

1
2
format.font = "Helvetica";
3
format.size = 12;
4
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.

1
2
private function loadComplete(e:Event):void
3
{
4
	suggestions = e.target.data.split(","); //The split method separates the words using as delimiter the ","

5
}

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.

1
2
private function suggest(e:KeyboardEvent):void
3
{

Step 21: Reset

The first thing to do is clear the suggested array, this will erase the previous suggestions (if any).

1
2
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.

1
2
for (var j:int = 0; j < suggestions.length; j++)
3
{
4
	if (suggestions[j].indexOf(inputField.text.toLowerCase()) == 0)//indexOf returns 0 if the letter is found

5
	{

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.

1
2
		var term:TextField = new TextField();
3
4
		term.width = 100;
5
		term.height = 20;
6
		term.x = 75;
7
		term.y = (20 * suggested.length) + 88;//Positions the textfield under the last one

8
		term.border = true;             /* Here we use the border property

9
		term.borderColor = 0x353535;       to separate the textfields */
10
		term.background = true;
11
		term.backgroundColor = 0x282828;
12
		term.textColor = 0xEEEEEE;
13
		term.defaultTextFormat = format;//Set the previously created format

14
15
		//Mouse Listeners

16
		term.addEventListener(MouseEvent.MOUSE_UP, useWord);
17
		term.addEventListener(MouseEvent.MOUSE_OVER, hover);
18
		term.addEventListener(MouseEvent.MOUSE_OUT, out);
19
20
		addChild(term);
21
		textfields.push(term); //Adds the textfield to the textfields array

22
23
		suggested.push(suggestions[j]);
24
25
		term.text = suggestions[j]; //Sets the found suggestion in the textfield

26
	}
27
				
28
}

Step 24: Clear TextFields

If the user deletes the letters in the Input Field, the suggestions are removed.

1
2
if (inputField.length == 0) //input field is empty

3
{
4
	suggested = []; //clear arrays

5
6
	for (var k:int = 0; k < textfields.length; k++)
7
	{
8
		removeChild(textfields[k]); //remove textfields

9
	}
10
11
	textfields = [];
12
}

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.

1
2
	if(e.keyCode == Keyboard.DOWN && currentSelection < textfields.length-1)
3
	{
4
		currentSelection++;
5
		textfields[currentSelection].textColor = 0xFFCC00;
6
	}
7
			
8
	if(e.keyCode == Keyboard.UP && currentSelection > 0)
9
	{
10
		currentSelection--;
11
		textfields[currentSelection].textColor = 0xFFCC00;
12
	}
13
			
14
	if(e.keyCode == Keyboard.ENTER)
15
	{
16
		inputField.text = textfields[currentSelection].text;
17
				
18
		suggested = [];
19
20
		for (var l:int = 0; l < textfields.length; l++)
21
		{
22
					removeChild(textfields[l]);
23
		}
24
25
		textfields = [];
26
		currentSelection = 0;
27
	}
28
}

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?

1
2
private function useWord(e:MouseEvent):void
3
{
4
	inputField.text = e.target.text;
5
6
	suggested = [];
7
8
	for (var i:int = 0; i < textfields.length; i++)
9
	{
10
		removeChild(textfields[i]);
11
	}
12
13
	textfields = [];
14
}
15
16
private function hover(e:MouseEvent):void
17
{
18
	e.target.textColor = 0xFFCC00;
19
}
20
21
private function out(e:MouseEvent):void
22
{
23
	e.target.textColor = 0xEEEEEE;
24
}

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!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.