I want to have a component where i can enter numeric values with decimal places like prices. How to writ such a component ?
All you need for this is a TextInput with a CurrencyFormatter. Use the keyDown event to intercept any alphabetic keys that are pressed. Then whenever focus is lost on the component or the Enter key is pressed format the text.
So first setup a TextInput that listens to three events:
<s:TextInput id="txtInput" text="{formatter.format(0)}"
keyDown="txtInput_keyDownHandler(event)"
enter="txtInput_enterHandler(event)"
focusOut="txtInput_focusOutHandler(event)"/>
The enterHandler and focusOutHandler are both the same and very simple:
protected function txtInput_enterHandler(event:FlexEvent):void
{
txtInput.text = formatter.format(txtInput.text);
}
protected function txtInput_focusOutHandler(event:FocusEvent):void
{
txtInput.text = formatter.format(txtInput.text);
}
The keyDownHandler is a little more complicated. The basis of this handler is to see if the person typed a number or period and if not then don't allow that character in the text of the TextInput. So first convert the charCode for the keyDown to the appropriate string:
var tempString:String = String.fromCharCode(event.charCode);
Then you will do a RegEx test to see if that is a digit or period. If it is anything other than a digit or period then use the preventDefault method to prevent the text from being added to the TextInput.text property.
var re:RegExp = /[0-9.]/;
if (tempString.search(re) == -1) {
event.preventDefault();
}
The one problem with this is that it intercepts the tab button as well which helps to trigger the focusOutHandler. So add an extra conditional outside of that to detect if Tab is pressed:
if (event.charCode != Keyboard.TAB) {
}
Then it is just a matter of setting up your Formatter accordingly and you are set to go. I built a custom component and added it to my meager, but growing, library which is available on Google Code at http://code.google.com/p/day2daydevelopment/ The component is
com.day2daydevelopment.components.NumberFormatInput.mxml
+