views:

162

answers:

2

I have a script that parses some complex XML. When the XML element is of a certain type, it generates a comboBox using the XML element's children to populate the box. I then want to check all of the values of the all the generated ComboBoxes against their correct answers (which is also info stored in the XML file). When creating the ComboBoxes, I added an "id" property. However, it seems that I cannot them use:

dynamicQuestion.id.selectedItem.labelField

to check the answers. However, I am able to get the labelField if I know the variable name used to create the ComboBox.

dynamicQuestion.selectedItem.labelField

This indicates (to me) that I need to dynamically generate the variable name as I'm creating new instances of the ComboBox. But how do I dynamically generate a variable name? If I use

var thisBox:String = "box"+boxCount;
var newBox:ComboBox = thisBox as ComboBox;

I get an implicit coercion error. I also tried changing the creation statement to a function that accepted an argument, "thisBox," but this didn't work either. Conceptually, this seems quite simple, but I'm having a hard time putting it to practice. It seems that the comboBox's id is what is generated by created the box using script (e.g., var thisBox). How do I dynamically generate this name?

A: 

Why don't you store all your dynamically created combo boxes in an array? When you want to evaluate them you iterate over the array and access selectedItem.labelField.

Stefan
+1  A: 

Use an array as Stefan suggested. If you must use string identifiers, you can create an object and use it as an associative array.

var combos:Object = {};

var boxCount:Number = 1;
var thisBox:String = "box"+boxCount;
//you can store comboboxes in the object using the following syntax
combos[thisBox] = new ComboBox();
//or
combos.box2 = new ComboBox();
//or
combos["box3"] = new ComboBox();

trace(combos.box1.selectedItem.labelField);
trace(combos.box2.selectedItem.labelField);
trace(combos.box3.selectedItem.labelField);
Amarghosh
Amarghosh, this is exactly what I was trying to do. In the meantime, though, we ended up going with a different solution. We set a name property on each ComboBox created and used getElementByName to then access the info, which worked just as well.
staypuffinpc
assuming you are talking about `getChildByName`, make sure there aren't any duplicate names. That method will just return the top most one if there are duplicates - which may or may not be the one you want.
Amarghosh