martedì 25 marzo 2014

No more than a dot in numeric TextField.

I needed to limit the input of a numeric TextField to a single dot and not allow it to be the first char.
So after a while I solved my problem writing down this:


import flash.events.MouseEvent;
import flash.text.TextFormatAlign;

/* Create an instance of a TextField */ 

var inputField:TextField = new TextField(); 

    /* Set text and properties */ 
inputField.text="0.5";
inputField.restrict = "0-9 .";
inputField.maxChars = 5;
    inputField.type = "input";
inputField.width = inputField.width +5;
inputField.height = inputField.textHeight +5;
    inputField.x = (stage.stageWidth - inputField.width)/2;
    inputField.y = (stage.stageHeight - inputField.height)/2;
inputField.backgroundColor = 0x444444; 
inputField.background = true; 

/* Set other properties with TextFormat class */

var tF:TextFormat = new TextFormat();
tF.color = 0x9F9F9F;
tF.bold=true;1
tF.size=15;
tF.align = TextFormatAlign.CENTER;
inputField.setTextFormat(tF)

/* Make your textfield visible */ 
addChild(inputField); 

/* Link the TextField to textInputHandler function */

inputField.addEventListener(Event.CHANGE, textInputHandler); 


/* If first char is a dot or the string contains more than one dot. */ 

function textInputHandler (e:Event) {

var string:String = e.target.text;
var idx:int=string.indexOf(".");
var last:String=string.substr(string.length-1,string.length);

if (idx != -1) {
if ((string.charAt(string.length - 1) == string.charAt(idx) && (string.length - 1) != idx) || (string == last)) {
e.target.text = string.substr(0,string.length -1);
}

    }

}


Nessun commento:

Posta un commento