Use an associative array to build the list.
This example requires a *MovieClip in the library for the button: class export name "Btn".
*
must be MovieClip; Button symbol will not work for this.
This script goes on frame1 of the main timeline.
ActionScript Code:
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.MouseEvent;
// container for the list
var list:Sprite = new Sprite();
// list of quantity textfields
var quantityArray:Array = new Array();
// list of items: name | price | quantity
var itemsArray:Array =
[
{name:"item1", price:1.99, quantity:0},
{name:"item2", price:2.99, quantity:0},
{name:"item3", price:3.99, quantity:0},
{name:"item4", price:4.99, quantity:0},
{name:"item5", price:5.99, quantity:0}
];
// build the lost; pass in the number of items
buildList(itemsArray.length);
function buildList(n:int):void
{
var row:Sprite;
var btn:Btn;
var nf:TextField;
var pf:TextField;
var qf:TextField;
var padX:int = 5;
var padY:int = 20;
var rowY:Number = 0;
for (var i:int = 0; i < n; i++)
{
row = new Sprite();
// the button
btn = makeBTN(i);
// name field
nf = makeTF(itemsArray[i].name);
nf.x = btn.width + padX;
nf.y = btn.height/2 - nf.height/2;
// price field
pf = makeTF(itemsArray[i].price);
pf.x = nf.x + nf.width + padX;
pf.y = nf.y;
// quantity field
qf = makeTF(itemsArray[i].quantity);
qf.x = pf.x + pf.width + padX;
qf.y = nf.y;
// array of quantity fields
quantityArray[i] = qf;
// construct the row, then add the row to the list
row.addChild(btn);
row.addChild(nf);
row.addChild(pf);
row.addChild(qf);
row.y = rowY;
list.addChild(row);
rowY = list.height + padY;
}
list.x = stage.stageWidth/2 - list.width/2;
list.y = stage.stageHeight/2 - list.height/2;
addChild(list);
}
function updateQuantity(e:MouseEvent):void
{
// convert the text to Number, add 1, then assign to textfield as a String
var q:Number = Number(quantityArray[e.currentTarget.id].text);
q++;
quantityArray[e.currentTarget.id].text = q.toString();
}
// utility function for making the textfields
function makeTF(s:String):TextField
{
var padY:int = 5;
var padT:int = 10;
var tf:TextField = new TextField();
tf.text = s.toString();
tf.width = tf.textWidth + padT;
tf.height = tf.textHeight + padY;
return tf;
}
// utility function for making the buttons
function makeBTN(_id:int):Btn
{
var b:Btn = new Btn();
b.id = _id;
b.buttonMode = true;
b.mouseChildren = false;
b.addEventListener(MouseEvent.CLICK, updateQuantity);
return b;
}