Modified version of Zoids custom combo box to allow preselected value

This post is more than 2 years old.

Wow that title sounds complex. If you don't remember, a few hours ago I blogged about an article that Boyzoid wrote about how easy it was to do a custom component in Flex 2. His example added a new method to ComboBox, selectedItemByValue.

What if you wanted to set the selected item when the component is created? I made these modifications to Zoid's code:

<?xml version="1.0" encoding="utf-8"?> <mx:ComboBox xmlns:mx="" creationComplete="checkSelected()">

<mx:Script> <![CDATA[ [Bindable] public var defaultSelectedValue:int;

public function selectedItemByValue(val:int):void{ for (var i:int=0;i<this.dataProvider.length;i++){ var item:int = this.dataProvider[i].data;

	if(item == val){
		this.selectedIndex = i;
	} else{ this.selectedIndex = 0;}


private function checkSelected():void { selectedItemByValue(defaultSelectedValue); } ]]> </mx:Script>


Note first the use of creationComplete in the top tag. That just means - run checkSelected() when done. I then created a new public variable named defaultSelectedValue. My checkSelected function simply then calls the function Boyzoid had written. This then lets me do the following in the calling code:

<comp:customComboBox dataProvider="{comboData}" id="myCombo2" defaultSelectedValue="2" /> <comp:customComboBox dataProvider="{comboData}" id="myCombo3" defaultSelectedValue="3" /> <comp:customComboBox dataProvider="{comboData}" id="myCombo4" />

Not sure if this is best practice or not - and I did guess at a few things, but I thought I'd share.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA