tags:

views:

31

answers:

3

I have a combobox with values;

ONE          
TWO           
THREE

And I am using labelFunction to display it as formatted value;

 SELECT  ONE
 SELECT TWO
 SELECT THREE

So when I use selectedItem from the combo I get SELECT ONE as a value instead of just ONE

What would be the proper way to use the labelFunction just to display data but at the background save the real passed values?

+1  A: 

As per the docs, selectedItem should return the item and not the label; there is a selectedLabel property for fetching the label.

As a workaround, fetch the selectedIndex and use it as an index on the dataProvider to get the item at that index.

trace(comboBoxDataProvider.getItemAt(comboBox.selectedIndex));
Amarghosh
A: 

Hi,

The labelFunction only affects the visible label and doesn't touch the data, so you can still use selectedItem in the same way.

Here's a quick example of a labelFunction that will solve your requirement:

<fx:Script>
    <![CDATA[
        private function comboBoxLabelFunction(item:Object):String
        {
            return 'SELECT ' + item.toString();
        }
    ]]>
</fx:Script>

<s:ComboBox id="comboBox" dataProvider="{new ArrayCollection(['ONE','TWO','THREE'])}" labelFunction="comboBoxLabelFunction" />

Adding:

Alert.show(comboBox.selectedItem.toString());

To the change event on the combo box demonstrates that the selectedItem is untouched.

Cheers,

simon

Simon Gladman
+1  A: 

Idea is to fill dataProvider with Object (or other custom class instances):

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    initialize="init();">

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

        private function init():void
        {
            var array:Array = 
                [
                    { data: "ONE" },
                    { data: "TWO" },
                    { data: "THREE" }
                ];
            var collection:ArrayCollection = new ArrayCollection(array);
            comboBox.dataProvider = collection;
        }

        private function myLabelFunction(object:Object):String
        {
            return "SELECTED " + object.data; 
        }

        private function comboBox_changeHandler(event:ListEvent):void
        {
            trace(comboBox.selectedItem.data); // ONE
        }

    ]]>
    </mx:Script>

    <mx:ComboBox id="comboBox" labelFunction="{myLabelFunction}" 
        change="comboBox_changeHandler(event)"/>

</mx:Application>
Maxim Kachurovskiy