AS3 — Creating TextFields in a loop. Also with dynamic variable names

Judging by the amount of keywords my other AS3 post picked up like “Creating a new text loop in AS3”, I was obliged to answer.

Well, creating textfields in a loop is quite simple. Lets define a bare-minimum TextFormat outside of our loop (unless it needs to change per iteration).

var textFormat:TextFormat = new TextFormat("verdana", 11)

By the way, lets use our little trick we learned about assigning dynamic variable names to movieclips here because the same issue applies: we want access to our textfields in case we want to modify them later. The problem is that after this loop, we have no way of accessing them!

Let’s create an array to store our textfield and create a loop to generate our text fields.

var textFormat:TextFormat = new TextFormat("verdana", 11)

// lets create an array to store all of our textfield references.
var textArray:Array = new Arrray()

// and now the loop
for (var i:int; i < 3; i++) {
    var textField:TextField = new TextField()
    textField.defaultTextFormat = textFormat
    textField.text = 'This is my TextField' + i
    textField.x = 50*i
    addChild(textField)
    textArray.push(textField)
}

This would create 3 textFields with text: “This is my TextField0”, 1, 2.

We can now access those textfields (say the x position was too arbitrary) with our textArray.

textArray[0] = our first textField, textArray[1] = our second one, etc.
textArray[0].x = 500 // to access each object

Here’s a tip for having more useable text in the textFields. After all, the same thing plus a number is quite boring.

We can make another Array that holds the text each textField is supposed to have.

How about:

var text:Array = new Array('First TextField','TextField Two', 'Anything, really')

Now we can run through our loop again according to how many things are defined in our Array called text.

for (var i:int; i < text.length; i++) {
    var textField:TextField = new TextField()
    textField.defaultTextFormat = textFormat
    textField.text = text[i]
    textField.x = 50*i
    addChild(textField)
    textArray.push(textField)
}

This time, our loop will conveniently create as many textFields as you put in the “text” array. In retrospect, naming the textfield reference array textArray was a bad idea, as it forced me to use an uninformative name for the second array. It probably should have been something like: tfReferenceArray, and tfTextArray.

Hope something was useful. There are endless applications for this stuff.

28 Comments

  1. Russ says:

    Thank you so much. This is exactly what I needed.

  2. etuan says:

    Seems like I may have been able to figure out myself but you just saved me the hours of trial and error that it would have taken me. ยกMuchas Gracias Amigo!

  3. Johnny says:

    So there is no way to use:
    addChild (this[“textField”] + i); //or something similar to omit the arrays, and afterwards reference to the textField or MovieClip by variable name.
    Great job with both tutorials, I see that AS3 needs often more typing then AS1, but AVM2 must compensate me that. Thanx for help!

  4. Yuji says:

    Hey Johnny,

    I don’t know much about AS3 myself, but from looking around google for a long time, it doesn’t seem like you can dynamically create variable names for them.

    Please let me know if you find out otherwise!

    -Yuji

  5. Joren says:

    Awesome dood. I was diggin around trying to do this but i didnt know about the push method or whatever. Thanks for saving me unknown hours of messing with code. Now I just need to fit everything in a dynamic scroll bar. Thanks.

  6. let me know if you know any other method. it’s not permenet solution. if i want to do some process on that dynamic text fields then how can we do it.

  7. Yuji says:

    Alpesh Vaghasiya: Thanks for the comment. If you want to do something to those fields, work on the TextField Array (textArray in the example).

    textArray[0] = first TF, textArray[1] = second TF, etc.

  8. Jerome says:

    just to let you know that this echo flash cs3 errors all the way :

    for (var i:int; i < 3; i++) {
    var textField:TextField = new TextField()
    textField.DefaultTextFormat = textFormat
    textField.text = โ€˜This is my TextFieldโ€™ + i
    textField.x = 50*i
    addChild(textField)
    textArray.push(textField)
    }

  9. Yuji says:

    Hi Jerome, you are right. DefaultTextFormat should be defaultTextFormat, and the reason it won’t work if you copy and paste is because wordpress.com autoformats ‘ to `

  10. Yuji says:

    er, the wordpress autoformatted ‘ is a ` if pasted into something.

  11. jav666 says:

    thx for the idea!

  12. vfxmograf says:

    this works on papervision cubes too!!

  13. victor says:

    thank you..i think this help me, about how to initialize variable with loop

  14. Nuno says:

    Hello.

    I’m doing a game in AS3 and by coincidence I make the text fields in the same way as you. However, I have a problem. When I make the trace, returns me “[object TextField]. ” How do I distinguish a box from one position to another position in another?

    Thanks!

    1. Yuji says:

      By index – [0] is your first dynamically created box, [1] your second, etc.

      You could also trace the X or Y position of that box if you’d like!

      1. Daniel says:

        How do you trace the X or Y position of each text box? It looks like the text in the array is all added to one textbox, which is textField.

  15. DefaultTextFormat in textField.DefaultTextFormat = textFormat should be:

    defaultTextFormat

    1. Yuji says:

      Nice find! Thanks ๐Ÿ™‚

  16. Ali Tavakoli says:

    Thank you so much Yuji for your great site and useful tuts, always loved you man ๐Ÿ™‚

    I also got a news here that I thought would be so useful for all of us as Flash devs, Now that we are talking about TextField thought to let you know about a class that is so powerful and is extended from the Adobe TextField class itself.

    It’s named TextArea which allows you every possible tags even your own custom tag and has much more abilities too.

    Check out http://doitflash.com/ for more information.

    It not only allows you to load different SWF files by calling different tags in line of your text but also you have much more control over your Text blocks and its contents… such as calling your custom functions right from your text blocks and passing multiple and different arguments through them; loading talking avatars, video players, buttons, slideshows and more… by calling their own tags and having full interaction between all of the loaded SWF modules and your text block. Check out the site for more information, downloading the platform is also free of charge ๐Ÿ™‚

  17. eiko says:

    i dont understand at all ๐Ÿ˜ฆ

  18. Just desire to say your article is as astonishing. The clarity in your submit is simply nice and that i could suppose you are an expert on this subject. Well along with your permission let me to snatch your RSS feed to stay updated with impending post. Thank you a million and please carry on the rewarding work.

  19. ader says:

    Your code getting erorr on line 3 textField.defaultTextFormat = textFormat
    it should be textField.defaultTextFormat = TextFormat(); but it isn`t working this way.

  20. alpinist1974 says:

    Thanks, Yuji! Your code helped me to finally figure out something I’ve been trying to fix for a while.

    1. Yuji says:

      No problem! I’m still surprised this is helping people 4 years down the line.

      I feel like I’ve long forgotten this ๐Ÿ™‚

  21. ganesh says:

    thanks a lot, your code saved my life, can you post another article on how to take advantage MovieClip class in AS3
    Thanks

  22. you’re truly a good webmaster. The site loading velocity is amazing. It kind of feels that you’re
    doing any distinctive trick. In addition, The contents are masterwork.
    you have done a great activity in this topic!

  23. An impressive share! I’ve just forwarded this onto a friend who was conducting a little homework on this. And he actually bought me breakfast due to the fact that I discovered it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanks for spending the time to talk about this matter here on your blog.

  24. busty says:

    Your style is really unique in comparison to other folks I have
    read stuff from. Many thanks for posting when
    you’ve got the opportunity, Guess I’ll just book mark this blog.

Leave a reply to alpinist1974 Cancel reply