Jivago
Jivago

Reputation: 826

Select value of a DropDownList via actionscript in Flex 4

I'm sure this is a easy one but I've been searching for a while how to select a DropDownList element with actionscript. In this scenario, I'd like to be able to specify the selectedItem based either on ddlLabel or ddlData

<?xml version="1.0" encoding="utf-8"?>

<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.events.FlexEvent;

        [Bindable]
        protected var timezonesArray:ArrayCollection = new ArrayCollection([
            {ddlLabel:"Eastern Time", ddlData:"EST"}, 
            {ddlLabel:"Central Time", ddlData:"CST"}, 
            {ddlLabel:"Mountain Time", ddlData:"MST"}, 
            {ddlLabel:"Pacific Time", ddlData:"PST"}
        ]);

        protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
        {
            // I'm looking to select an element via actionscript here, based on ddlLabel or ddlData
        }

    ]]>
</fx:Script>

<mx:Form>
    <s:DropDownList id="ddlTimezones" dataProvider="{timezonesArray}" labelField="ddlLabel"/>
</mx:Form>

Upvotes: 2

Views: 7954

Answers (1)

Dan Monego
Dan Monego

Reputation: 10087

There are a couple ways to do this - if you need to do it using the label or the value, you can loop though the arraycollection like this:

protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
    var searchTerm:String = "EST";
    var result:* = null;
    for each(var zone:* in timeZonesArray)
    {
        if(searchTerm == zone.ddlData)
        {
            result = zone;
            break;
        }
    }
    ddlTimezones.selectedItem = result;
}

However, if you keep a reference to the time zones individually or you're getting them from some other part of the app, you can do it more cleanly:

import mx.collections.ArrayCollection;
import mx.events.FlexEvent;


var EST:Object = {ddlLabel:"Eastern Time", ddlData:"EST"};
var CST:Object = {ddlLabel:"Central Time", ddlData:"CST"};
var MST:Object = {ddlLabel:"Mountain Time", ddlData:"MST"};
var PST:Object = {ddlLabel:"Pacific Time", ddlData:"PST"};

[Bindable]
protected var timezonesArray:ArrayCollection = new ArrayCollection([
    EST, 
    CST, 
    MST, 
    PST
]);

protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
    ddlTimezones.selectedItem = EST;
}

This way, you don't have to worry about interrogating every object in the list, because you're staying at the level of whole objects rather than reaching into them. It also makes it easier if you want to replace your list of JSON style objects with a class definition, if you start needing to store more complicated information about time zones.

Upvotes: 3

Related Questions