Hammer
Hammer

Reputation: 17

Get Flex TextInput.text from dynamically created TextInput field

I am creating several TextInput boxes via a for loop similar to the one below. The NumberOfSelections variable will differ depending on input from the user.

    for(var i:int=1; i <= NumberOfSelections; i++){
            InputField = new TextInput;
            InputField.id = "Name" + i
            InputField.text = "2" 
            HGroup1.addElement(InputField);
    }

The TextInput text is editable when run, and the user will put in numbers and then press a calculate button that will call a new function. How do I get the information from all the TextInput fields. For instance, if NumberOfSelections was 4 how would I get all 4 numbers the user entered in order to add them together. Is it possible to use the unique id name

Many Thanks

Upvotes: 0

Views: 1225

Answers (3)

RIAstar
RIAstar

Reputation: 11912

Flextra's answer is definitly correct. I would just like to add two other options:

Loop over the HGroup's children

for (var i:i=0; i<hGroup1.numElements; i++) {
    var inputField:TextInput = hGroup1.getElementAt(i) as TextInput;
    if (inputField) doSomthingWith(inputField.text);    
}

Note that from a "best practices" point of view, this isn't a very pretty approach.
A somewhat nicer approach might be to

Ditch the dynamic instantiation and use a DataGroup instead

Because this is exactly what a DataGroup is meant to do.

<s:DataGroup dataProvider="{dp}">
    <s:itemRenderer>
        <fx:Component>
            <s:ItemRenderer>
                <s:TextInput text="@{data.myValue}"/>
            </s:ItemRenderer>
        </fx:Component>
    </s:itemRenderer>

    <s:layout>
        <s:HorizontalLayout/>
    </s:layout>
</s:DataGroup>

Note that the myValue property must be declared bindable for this to work.
You can now simply loop over the items in dp to do your calculations and let the framework handle the dynamic instantiation. If you need to add/remove a TextInput, just add/remove an item to dp. In my opinion this is by far the cleanest solution, because it nicely separates your view from your model.

Upvotes: 1

HugoLemos
HugoLemos

Reputation: 473

use [] to reference to yours inputs:

for(var i:int=1; i <= NumberOfSelections; i++){
    someVariable = this["Name" + i].text;
}

Upvotes: 0

JeffryHouser
JeffryHouser

Reputation: 39408

You must save a reference to the fields as you create them. I would suggest storing them in an array:

// somewhere in your code; define the variable
public var textBoxArray : Array = new Array();

// somewhere in some method create the textBoxes
for(var i:int=1; i <= NumberOfSelections; i++){
        InputField = new TextInput;
        InputField.id = "Name" + i
        InputField.text = "2" 
        HGroup1.addElement(InputField);
        textBoxArray.push(InputField);
}

Upvotes: 0

Related Questions