How to use TextFields as "Number Fields"?

Hello,

I have two TextFields on the stage. Actually I would like to use the two TextFields as Numbers. Therefore I can do some calculation of the two TextFields. Is it possible to do that? If yes, could you please provide some guidelines?

Thanks and best regards

Alex

One way would be to coerce the String value of the text into a Number, like so:

firstNumber = Number(myTextField.text);

You may also wish to look at using something like myTextField.restrict = “0-9”; to ensure only numbers are entered.

Hi dthought,

Thanks for your help. This is exactly what I need, and with one more extra bonus - myTextField.restrict = “0-9”;

I have one more question:

The stage has another dynamic TextField (output_txt). I wish to alert users that the myTextField is restrict to numbers only. When the users not enter numbers in the myTextField, a message (e.g. Only numbers are allowed) will appear in the output_txt TextField. How can I do that?

Thanks and best regards

Alex

Add a listener to myTextField for the Keyboard.KEY_DOWN event that checks that event.charCode is between 48 and 57:


import flash.events.KeyboardEvent;

myTextField.addEventListener(KeyboardEvent.KEY_DOWN, numberCheck);

function numberCheck(event:KeyboardEvent):void
{
    if (event.charCode >= 48 && event.charCode <= 57)
    {
        trace("User input is a number");
    }
    else
    {
        trace("User input is not a number");
    }
}

Hi all,

Thanks for your help. It works perfectly:)

Best regards

Alex

You can make use of validators in ActionScript 3.

<mx:NumberValidator source="{txtRent}" property=“text” required="true"
integerError=“Enter Integer value” minValue=“50” domain=“int”/>

You should use source as the textfield name. minValue is the minimum value that this textField will allow you. Same way you can also define maxValue.

Have fun!!
Manu.