Saturday, December 10, 2011

Flex: Jump to next field using the Focus Manager


The following example shows you how to use the FocusManager and how to set the focus to a TextInput using the setFocus() method.

In this example you can fill you birthday (MM/DD/YYYY) and the focus will jump to the next field automatically.

Listing 1
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" width="500" height="100">
    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            
            import spark.events.TextOperationEvent;
                    
            public function checkLengthAndFocus(event:TextOperationEvent):void              
            {
                if( event.currentTarget.id == "month" && event.currentTarget.text.length == 2 )
                {
                    focusManager.setFocus( day );
                }
                if( event.currentTarget.id == "day" && event.currentTarget.text.length == 2)
                {   
                    focusManager.setFocus( year );  
                }   
            }
        ]]>
    </fx:Script>
    <s:VGroup width="100%" height="100%" horizontalAlign="center" paddingBottom="5" 
              paddingLeft="5" paddingRight="5" paddingTop="20" >
        <s:Label text="Fill in your birthday (MM/DD/YYYY)" />
        <s:HGroup width="100%" height="100%" verticalAlign="middle" horizontalAlign="center"> 
            <s:TextInput id="month" width="23" change="checkLengthAndFocus(event)" />
            <s:TextInput id="day" width="23" change="checkLengthAndFocus(event)" />
            <s:TextInput id="year" width="46" maxChars="4" />
        </s:HGroup>
    </s:VGroup>
</s:Application>

No comments :

Post a Comment