TextField as3 getting the input - actionscript-3

i have a problem witch i cant solve, and i wanted to ask what am i doing wrong. The idea should be that when i create the textfield i want to read from it, but it doesnt
function click2(e:MouseEvent):void{
e.currentTarget.removeEventListener(MouseEvent.CLICK, click2);
fx=e.target.x+400;
fy=e.target.y+300;
var i:int;
i=2;
trace(str);
trace(e.target.name);
var line:Shape = new Shape();
line.graphics.lineStyle(1,0xFF0000,2);
line.graphics.moveTo(sx,sy);
line.graphics.lineTo(fx,fy);
this.addChild(line);
var inputField:TextField = new TextField();
inputField.border = true;
inputField.type = TextFieldType.INPUT;
inputField.width = 23;
inputField.height = 18;
inputField.x = (sx+fx)/2;
inputField.y = (sy+fy)/2;
inputField.multiline = false;
inputField.maxChars = 3;
inputField.restrict = "0-9";
str=inputField.text;
addChild(inputField);
}
In this code i create a line, and near it appears a textfield , where you need to input the value of the line, but i can`t get it , when i want to trace the STR value, it is null,the text should be written by the user and i should read it ...

If you want to check the data the user added to the textinput you have to listen for the change-event. After that you can access the provided text.
function click2(e:MouseEvent):void{
...
inputfield.addEventListener(Event.CHANGE, checkInput);
}
function checkInput(e:Event):void {
//receive input value and validate it
var textfield:TextField = e.target as TextField;
var str:String = textfield.text;
...
}

Related

event listener not being called

How can I resolve my problem?
I load all images and image buttons when I click on a button but after that when I try to click on close button (image4) the event listener cannot listen because everything is set in another function.
private function onShop(evt:MouseEvent)
{
shop.removeEventListener(MouseEvent.CLICK, onShop);
var container:Sprite = new Sprite();
var ibutton:Sprite = new Sprite();
addChild(container);
addChild(ibutton);
ibutton.buttonMode = true;
function loadImage(path:String):Loader
{
var request:URLRequest = new URLRequest(path);
var loader:Loader = new Loader();
loader.load(request);
return loader;
};
var image1 = loadImage("image/inventory/shop_windoww.png");
image1.x = 200;
image1.y = 40;
this.addChildAt(image1,8);
var image2 = loadImage("image/inventory/title_window.png");
image2.x = 200;
image2.y = 14;
container.addChild(image2);
var image3 = loadImage("image/inventory/icon_window.png");
image3.x = 177;
image3.y = 7;
container.addChild(image3);
var image4 = loadImage("image/inventory/close.png");
image4.x = 891;
image4.y = 39;
ibutton.addChild(image4);
var image5 = loadImage("image/inventory/button_ok.png");
image5.x = 450;
image5.y = 485;
ibutton.addChild(image5);
var image6 = loadImage("image/inventory/button_ok.png");
image6.x = 782;
image6.y = 485;
ibutton.addChild(image6);
image4.addEventListener(MouseEvent.CLICK, test);
}
private function test(evt:MouseEvent)
{
image4.removeEventListener(MouseEvent.CLICK, test);
trace("ca marche");
}
Declare your variables outside of the onShop scope. They seem to have more sense as global variables, not only local (because you are trying to use the same variables declared on the onShop method on test method).
I also recommend you some points:
Use an external file (JSON/XML) to get all image URLs, or just use a simple Array with hardcoded content;
Use a for loop to load all images (after following the previous suggestion);
Use event.currentTarget in your test method, so, you can deal with those images with a more generic way.
[event.currentTarget] The object that is actively processing the Event object with an event listener. For example, if a user clicks an OK button, the current target could be the node containing that button or one of its ancestors that has registered an event listener for that event.

Interaction isn't translating input Text to Strings

I'm in need of some help. To start with, what I have is an interaction where you fill out 5 text boxes in response to 2 questions. Each of the 5 answers must be filled out as input text and then checked against an array of acceptable responses when the done button is clicked. Also, there are two type differences in the fields. So the first three answer fields belong to a range of acceptable responses in the array: Type A and the next two questions to Type B. It's possible to fill out the correct responses in any order, so long as the typing is correct.
What I can't seem to figure out is why the textFields aren't translating to Strings.
import flash.text.TextField;
import flash.events.MouseEvent;
stop();
//*--------------------------------------------
//
// THINGS YOU CAN CHANGE
//
//*--------------------------------------------
var a_inputType:Array = new Array("Doggie Day Spa", "Deb's Dog Walking Service", "Pet Market", "Pampered Pet", "TLC Grooming"); //All recognized type responses, Type A listed before Type B
var n_typeA:Number = new Number(3); //Sets the range for Type A
//*--------------------------------------------
//
// PAGE SETUP
//
//*--------------------------------------------
var n_typeB:Number = new Number(a_inputType.length - n_typeA +1); //Finds the range of Type B
var a_testArray:Array = new Array(); //Holds push data from submit button
var a_correctArray:Array = new Array(); //Creates an array to run a final test against
for(var c = 0; c<=a_inputType.length-1; c++){ //Loop populates the array
a_correctArray.push(1);
}
var inputField1:TextField = new TextField(); //Creates the Text Fields
var inputField2:TextField = new TextField();
var inputField3:TextField = new TextField();
var inputField4:TextField = new TextField();
var inputField5:TextField = new TextField();
var txtString1:String = new String(); //Creates the strings for translating the input text
var txtString2:String = new String();
var txtString3:String = new String();
var txtString4:String = new String();
var txtString5:String = new String();
for(var f = 1; f<=a_inputType.length; f++){ //Assigns them properties, locations, and adds a listener for text
var fieldBuilder = "inputField"+f;
var fieldFinder = "txt_pos"+f;
addChild(this[fieldBuilder]);
this[fieldBuilder].border = false;
this[fieldBuilder].width = 290;
this[fieldBuilder].height = 25;
this[fieldBuilder].x = this[fieldFinder].x;
this[fieldBuilder].y = this[fieldFinder].y;
this[fieldBuilder].type = "input";
this[fieldBuilder].multiline = true;
this[fieldBuilder].text = "";
this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, function (){
var stringBuilder = "txtString"+f;
this[stringBuilder] = this[fieldBuilder].text;
});
}
//*--------------------------------------------
//
// FUNCTIONS
//
//*--------------------------------------------
function SUBMIT(event:MouseEvent):void{
for(var t=1; t<=a_inputType.length; t++){ //Loop establishes checks for each String against an input type
if(t<=n_typeA){ //if/else divides the textfields into two ranges: typeA and typeB
checkTypeA(this["txtString"+t], a_inputType); //sends the array of correct responses and the captured String to checkTypeA
}else{
checkTypeB(this["txtString"+t], a_inputType); //sends the array of correct responses and the captured String to checkTypeB
}
}
var TEMPSELECT = a_testArray.toString(); //reduces the testArray recieving push data into a String
var TEMPCORRECT = a_correctArray.toString(); //reduces the correctArray from scene set-up into a String
if(TEMPSELECT == TEMPCORRECT){ //compares the strings and determines a trace response
trace("correct");
}else{
trace("incorrect");
}
}
function checkTypeA(value:String, arr:Array){ //Checks the String against all the array values within the specified range for type A
for (var a=1; a<=n_typeA; a++){ //determines the range
if (arr[a]==value){ //checks the value
a_testArray.push(1); //if true, generates a push value for a testArray to be checked later
}
}
}
function checkTypeB(value:String, arr:Array){
for (var b = n_typeA; b<=n_typeB; b++){
if (arr[b-1]==value){
a_testArray.push(1);
}
}
}
//*--------------------------------------------
//
// BUTTONS
//
//*--------------------------------------------
done_bttn.addEventListener(MouseEvent.CLICK, SUBMIT); //Launches the SUBMIT function when "Done" is pressed.
Upon further investigation I've noticed that the loop isn't terminating when it reaches 5. It keeps regurgitating TextFields over and over again with the same variable names and instancing. Because of this, the addChild is dumping input fields one on top of one another in the flash file (which makes editing a text field impossible since your always clicking on a new field positioned directly on top of the one you just edited).
The trace on the loop comes back like this:
inputField1
txt_pos1
inputField2
txt_pos2
inputField3
txt_pos3
inputField4
txt_pos4
inputField5
txt_pos5
inputField1
txt_pos1
inputField2
txt_pos2
inputField3
txt_pos3
inputField4
txt_pos4
inputField5
txt_pos5
inputField1
txt_pos1
inputField2
txt_pos2
and so on.... how can I stop this looping behavior. I've tried if/else breaking and that's not working.
The context of the this keyword changes when you call it from a local function. You can easily verify it if you add trace(this) to your anonymous function. It will trace out [object global]. Two solutions come to mind, store a reference of this in a variable:
var self:MovieClip = this;
for(var f = 1; f<=a_inputType.length; f++){
//...
this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, function (){
var stringBuilder = "txtString"+f;
self[stringBuilder] = self[fieldBuilder].text;
});
}
Or declare a new function:
for(var f = 1; f<=a_inputType.length; f++){
//...
this[fieldBuilder].addEventListener(TextEvent.TEXT_INPUT, myFunction);
}
function myFunction(t:TextEvent){
var stringBuilder = "txtString"+f;
this[stringBuilder] = (t.target as TextField).text;
}

Match two strings from a text file and user input? (AS3)

I was able to load a text file in a Flash file, but I am unable to match two strings from a text file and the user input.
The purpose of this AS3 code: to match the text file and user input, and if it matches, the score will increase by 1. Else, the score will increase by 0.
Here is my code:
var uScore :Number = 0;
stop();
var textLoader:URLLoader = new URLLoader();
var textURLRequest:URLRequest = new URLRequest("q1.txt");
textLoader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void
{
var textData:String = new String(textLoader.data);
dy1.text = textData;
}
textLoader.load(textURLRequest);
function goURL(event:MouseEvent):void {
var textLoader2:URLLoader = new URLLoader();
var textURLRequest2:URLRequest = new URLRequest("answer1.txt");
var textData2:String = new String(textLoader2.data);
var name1 = trace(textData2);
textLoader2.load(textURLRequest2);
var myURL = url1.text;
if(myURL == name1){
uScore += 1;
uScoreURL.text = uScore+"";
nextFrame();
}
else{
uScore+=0;
uScoreURL.text = uScore+"";
nextFrame();
}
}
trace(uScore);
You code has a strange assignment:
var name1 = trace(textData2);
replace it with
var name1 =textData2;
it should work then if there isn't a bug in some other place.
And you don't need to uScore+=0;. Just delete it.
I checked out your code, you were doing a few things out of order - here is the revised code that should get you where you need to be
var uScore :Number = 0;
stop();
var textLoader:URLLoader = new URLLoader();
var textURLRequest:URLRequest = new URLRequest("q1.txt");
textLoader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void
{
var textData:String = new String(textLoader.data);
dy1.text = textData;
}
textLoader.load(textURLRequest);
btn.addEventListener(MouseEvent.CLICK,getNumber);
var textLoader2:URLLoader = new URLLoader();
textLoader2.addEventListener(Event.COMPLETE, completeHandler2);
function completeHandler2(event:Event):void
{
var textData2:String = new String(textLoader2.data);
var name1 = textData2;
trace(name1);
var myURL = url1.text;
if(myURL == name1){
uScore += 1;
uScoreURL.text = uScore+"";
nextFrame();
}
else{
uScore+=0;
uScoreURL.text = uScore+"";
nextFrame();
}
}
function getNumber(event:MouseEvent){
var textURLRequest2:URLRequest = new URLRequest("answer1.txt");
textLoader2.load(textURLRequest2);
}
trace(uScore);
The only thing that I really added that you didn't have is a button with the variable name btn to check the answer - you can rework that to however you want to check for the answer.

Change font-color of TextField inside MovieClip

I've a problem to change the font-color of a TextField after it has been added as a child to a MovieClip.
My code:
var btn:MovieClip = new MovieClip();
// other code for button
var tf:TextFormat = new TextFormat();
tf.size = 12;
tf.bold = true;
tf.font = "Arial"
tf.color = 0x000000;
var capt:TextField = new TextField();
capt.defaultTextFormat = tf;
capt.width = 200;
capt.height = 50;
capt.text = "Test";
capt.y = 20;
capt.x = 20;
capt.border = false;
capt.selectable = false;
btn.addChild(capt);
// .....
How can I Change the font-color after the last line?
It sounds like you're looking for TextField.setTextFormat(). You can either adjust your original TextFormat or just make a whole new one.
tf.color = 0xFF0000;
capt.setTextFormat(tf);
Assuming the TextField falls out of scope after that last line (you don't show enough to know if it does or not), you'll need to loop through the button to get the TextField and do it from there.
var i:uint;
var l:uint = btn.numChildren; //numChildren and length are 'heavy' getters, never use them as restrictors in a loop
for ( i = 0; i < l; i++ ) {
var cur:DisplayObject = btn.getChildAt( i );
if ( cur is TextField ) {
( cur as TextField ).setTextFormat( /*set new TextFormat in here*/);
break;
}
}
That assumes there is only the single TextField, of course. If there are multiple, I would extend MovieClip and add a public property for the value you want to change.
You can also just use the textColor property of a textfield:
capt.textColor = 0xFF0000;

AS3 Adobe AIR: Return xml string

I'm working in Flash CS6 with Adobe AIR 3.3 (for iOS) and having trouble returning an XML string to a textField.
It is tracing the proper information, and I've tried a few ways to return the trace but can't seem to quite get it... Here is my most recent try. Any suggestions? Thanks in advance.
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("http://www.someURL.php"));
//php file that echos xml
myLoader.addEventListener(Event.COMPLETE, init);
var fadedText:TextField;
var touchList:TouchList;
var textOutput:TextField;
var animateLeft:Tween;
var listArray:Array;
var item:TouchListItemRenderer;
var theXML:XML;
var days:Array = new Array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
var daySelected;
var businessNameArray:Array = new Array();
var businessLogoArray:Array = new Array();
var businessAddress:Array = new Array();
var distanceArrayDisplay:Array = new Array();
var distanceArrayCount = 0;
function init(e:Event = null):void
{
trace(myLoader.data);
theXML = new XML(e.target.data);
theXML.ignoreWhitespace = true;
myLoader.close();
// add our list and listener
var itemSizeCalculator = stage.stageHeight / 6;
touchList = new TouchList(stage.stageWidth, stage.stageHeight-itemSizeCalculator);
touchList.addEventListener(ListItemEvent.ITEM_SELECTED, handlelistItemSelected);
addChild(touchList);
touchList.x = stage.stageWidth;
// Fill our list with item rendreres that extend ITouchListRenderer.
for(var i:int = 0; i < theXML.food.length(); i++) {
if(theXML.food[i].monday != "un")
{
item = new TouchListItemRenderer();
item.index = i;
item.data = theXML.food[i].business;
item.name = theXML.food[i].business;
item.addEventListener(MouseEvent.CLICK, itemWasClicked);
item.itemHeight = itemSizeCalculator;
businessNameArray[i]= theXML.food[i].business;
businessLogoArray[i]=("http://www.logosURL.com/"+theXML.food[i].logo);
businessAddress[i]= theXML.food[i].address;
var fadedTextFormat:TextFormat = new TextFormat();
fadedTextFormat.bold = true;
fadedTextFormat.color = 0x999999;
fadedTextFormat.size = 14;
fadedTextFormat.font = "Helvetica";
fadedText = new TextField();
fadedText.height = 30;
fadedText.mouseEnabled = false;
fadedText.defaultTextFormat = fadedTextFormat;
item.addChild(fadedText);
fadedText.x = 75;
fadedText.y = 10;
distanceArrayDisplay.push(fadedText);
var distanceLoader:URLLoader = new URLLoader();
distanceLoader.load(new URLRequest("http://maps.googleapis.com&origins=someAddress&destinations="+businessAddress[i]+"&mode=walking&language=en-en&sensor=false"));
distanceLoader.addEventListener(Event.COMPLETE, distanceCalculated);
var logoLoader:Loader = new Loader();
item.addChild(logoLoader);
var logoURL:URLRequest = new URLRequest("http://www.myLogos.com/"+theXML.food[i].logo);
logoLoader.load(logoURL);
logoLoader.scaleX = .4;
logoLoader.scaleY = .4;
logoLoader.y = logoLoader.y + 5;
logoLoader.mouseEnabled = false;
var arrowGraphic:rightArrow = new rightArrow();
item.addChild(arrowGraphic);
arrowGraphic.x = stage.stageWidth - 5;
arrowGraphic.y = item.height/2;
touchList.addListItem(item);
}
}
}
function distanceCalculated(e:Event)
{
// trace(e.currentTarget.data);
var distanceXML:XML = new XML(e.target.data);
distanceXML.ignoreWhitespace = true;
var returnVar:String = (distanceXML.row.element.distance.text);
distanceArrayDisplay[distanceArrayCount].text = returnVar;
trace(returnVar);
distanceArrayCount++;
}
I am guessing that you are correctly reading the first XML, and that XML has a list of URLs that you want to load and then display some info from those on TextFields. Without knowing the structure of that XML I can't suggest you any working code, but I can point you on the right direction. For more info on reading/iterating XML on flash as3, please read: http://www.kirupa.com/developer/flashcs3/using_xml_as3_pg1.htm
//iterator var
var xml_read:uint=0;
//array of textfields for reference
var array_textFields:Array;
//config XML complete
function init(e:Event = null):void
{
array_textFields = new Array();
theXML = new XML(e.target.data);
theXML.ignoreWhitespace = true;
//this depends on the XML structure, please look at the article I linked
//for more info on how to iterate an XML
var i:uint=0;
for(someUrl in theXML..url)
{
var fadedText:TextField = new TextField();
//you should place each Textfield on different coord, otherwise
//they will all stack on top of each other and you will only see one
//for example:
fadedText.y = (fadedText.height+10)*i;
item.addChild(fadedText);
array_textFields.push(fadedText);
var distanceLoader:URLLoader = new URLLoader();
distanceLoader.load(new URLRequest(someUrl));
distanceLoader.addEventListener(Event.COMPLETE, distanceCalculated);
i++;
}
}
function distanceCalculated(e:Event):void
{
var distanceXML:XML = new XML(e.target.data);
distanceXML.ignoreWhitespace = true;
//retrieve information
var returnVar:String = (distanceXML.row.element.distance.text);
//set to textfield
TextField(array_textFields[xml_read]) = returnVar;
//increase iterator
xml_read++;
}
Please bear in mind that in ActionScript3, all network I/O is asynchronous. Usually EventListener functions don't return any value because you don't know when the data is ready. What you do is store a reference to where you want the data to go (in your case, a TextField variable) when the EventListener function is called asynchronously.