bgx:components logo
© 2004 -2005
Bernhard Gaul



Navigate through TextInput fields by hitting ENTER or TAB (Flash MX 2004)

The following is an example of how to navigate from one TextInput field to another one (or any other UI Component) by using the TAB key and also the ENTER key.

For the TAB key it is enough to define the navigation order by defining the tabIndex properties of the TextInput fields.

To do something similar for the ENTER key without having to add listeners to each TextInput I created an Object that works as "HashTable", identifying for each TextInput the control that should be focused next.

This way I can add a generic keyListener that checks if the currently focused control is in the FocusHash and, if it is, sets focus to the associated control.

Warning: This works well as long as I don't try to set focus to a TextInput when the frame is loaded. You can set initial focus e.g. to tb0 by using e.g. tb0.setFocus() or _root.focusManager.setFocus(tb0) but that has the following side effects:

  • The TextInput tb0 must be loaded on a frame before calling tb0.setFocus() (or some other delay mechanism has to be used)
  • You won't see the Input Cursor in tb0 nor the green highlight, it only means if you type it will go straight to tb0
  • It totally messes up the script below

So for this example the user actually has to click into any of the TextInputs. If you have a better solution please let me know at info@bgxcomponents.com

The Code


//set tab index to move using the TAB key
tb0.tabIndex = 1;
tb1.tabIndex = 2;
tb2.tabIndex = 3;
btn.tabIndex = 4;
//create HashTable to identify successive //TextInput for each control var FocusHash = new Object(); FocusHash[tb0] = tb1; FocusHash[tb1] = tb2; //Note tb2 is a TextArea which shall insert a newline on ENTER //therefore it is not entered into the FocusHash //listen to the ENTER key var keyListener = new Object(); keyListener.onKeyUp = function(evt) { if (Key.getCode() == 13)) { //check if we have an entry for the currently focused //control in the FocusHash var thisFocusEntry = FocusHash[_root.focusManager.getFocus()]; if (typeof thisFocusEntry != "undefined") { thisFocusEntry.setFocus(); } } } Key.addListener(keyListener);

The Example

 

 

History

18-Nov-2004 : Changed event handler from onKeyDown to onKeyUp because otherwise Flash inserts a newline if the newly focused control is a TextArea.