Search code examples
actionscript-3apache-flexformattingflex4.5textinput

How to provide an inline TextInput formatting template


I have a spark TextInput control that I would like to automatically format as the user types into it. The format is something like XX-XX-XXX-XXX where each X is a digit.

I have create a custom Formatter that I am using to display these values in other locations, but I'm having trouble getting an elegant solution to provide this sort of automated formatting in the TextInput control itself.

Here is the code that I current have. It works, but when the formatter inserts one of the hyphen, the insertion point of the TextInput does not advance, so the next digit gets inserted in the next-to-last position.

<fx:Script>
  protected function changeHandler(event:TextOperationEvent):void
  {
    itemID.text = formatter.format(itemID.text);
  }
</fx:Script>

<fx:Declarations>
  <formatters:MyFormatter id="formatter" separator="-" pattern="{[2,2,3,3]}" />
</fx:Declarations>

<s:Form>
  <s:FormItem label="Item ID:">
    <s:TextInput id="itemID" restrict="0-9" change="changeHandler(event)" prompt="ex. xx-xx-xxx-xxx" /> 
  </s:FormItem>
</s:Form>

Here is the result of typing in the characters 1,2,3,4,5,6,7,8,9,0 in sequence. As you can see, the insertion point is three characters from the end which corresponds to the three inserted hyphens.

Example showing incorrect character insertion

Any suggestions on creating a smooth UX here?


Solution

  • If you itemID is a TextField based class use this:

    itemID.setSelection(itemID.length, itemID.length);
    

    It will move the caret to the end of the TF.