setFocus Issue on TextInput – Solution

Some days back, I got a mail from a customer with a baffling problem. Consider this…

  • You have 3 TextInputs, adjacent in tab order in an application.
  • You type something on the first, press tab, again type something on the next and tab again
  • Now for some reason, you want the second tab to switch focus onto the first, instead of the last TextInput…

He wrote a listener for the focusOut event on TextInput2 and then wrote the following code in the listener function.

stage.focus = txt1;

He expected this…

But got this…

After lots of digging, I found the solution, thanks to Sreeni 🙂

It seems that the problem is that though the application focus moves to TextInput1, the keyboard focus moves to TextInput3, as the keyboard foucs is moved before the focusOut method is called and we are able to call preventDefault() on it.

Sreeni dug out a KEY_FOCUS_CHANGE event which needs to be listened to, on TextInput2 and then repeated the above code for the event-listener method. So,

Instead of writing

<mx:TextInput id=”txt2″ focusOut=”setTxtFocus(event)”/>

You need to write the following code in the creationComplete Listener in AS

txt2.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, setTxtFocus);

Now you can repeat the same code for the setTxtFocus method and solve this issue… You can see the app and the solution code below

Application | Source


4 Responses to setFocus Issue on TextInput – Solution

  1. Harsha Pande says:

    I tried the application, which works if I tab out of the second text fielf control but does not work if i mouse click on the third text field.

  2. raghunathrao says:

    @ Harsha – Yes, it is a bug. I have logged it in the Flex public bugbase –

  3. Kanu Wadhwa says:

    In AIR its a default functionality that if u press any key it selects that file which starts whith the same character
    so when i click ctrl c, its set focus on the file which starts with c,whereas i want to set focus on the file which i had selected.
    if(event.controlKey || event.commandKey || event.ctrlKey){
    if(event.keyCode == Keyboard.C){
    if(event.keyCode == Keyboard.V){
    any suggestions?

  4. sheetal says:

    Thanks for sharing this issue and the solution off course.Few days back i encountered this issue while using textInput as itemRenderers in a Datagrid.But i coulnt solve it.Good to see the issue resolved.Thanks a lot.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s