There are several Flex components for handling auto completion out there, for example components called CompletionInput, Autocomplete TextInput or Adobes AutoComplete Input. For a current Flex 3 based project I decided to use Adobes component and had the following issue:

If you select the first item of the results pressing ENTER or just clicking by mouse, you will “lost” the value of the selected item. That means, it won’t be shown at the TextInput located on the top.

It seems, that this issues appears using Flex 3 only (not Flex 2).

Example

For testing both components:
1) Type just a “b” in one of the TextFields
2a) Press ENTER
2b) Or select just the first item clicking by mouse.
3) Compare the behavior of both components.

Get Adobe Flash player

 

Solution

To show the label of the selected item within the TextField just override the method called close of the com.adobe.flex.extras.controls.AutoComplete which extends the mx.controls.ComboBox.

close() method ( Download code )

  1. /**
  2. *  Closes the combox and set the selection which is lost using Flex 3
  3. *
  4. *  @event  Event Trigger event to close the combobox
  5. */     
  6. override public function close(event:Event = null):void
  7. {
  8.     super.close(event);
  9.    
  10.     if(selectedIndex == 0)
  11.     {
  12.         // set the text using the selected label
  13.         textInput.text = selectedLabel;
  14.         // select the text from typed text position to texts length
  15.         textInput.setSelection(cursorPosition, textInput.text.length);      
  16.     }
  17.           
  18. }

Download full source

Full source of the example above: AutoCompleteSample.zip (Downloads: 6005)

59 Responses to “Quick tip: Avoid issues using Adobes AutoComplete Input component using Flex 3”

  1. kilgore Says:

    That’s pretty good improvement. Thanks !

  2. David Repas Says:

    Anyone have any thoughts on how to feed an autocomplete from a database that has tens of thousands of records?

    I’m using ColdFusion w/ Flash remoting and MSSQL.

    Thanks,
    David

  3. microgluf Says:

    Wow, nice. Thanks Jens.

    David,
    Regarding the feed a lot of records, I have been very successful with 500k+ records by using stored procedures that would be triggered only after a set amount of characters… eg. 3 letters.. then trigger the search.
    For some specific cases I used a special table that was computed off-line, but that has algorithms and it’s beyond the scope…

  4. Max Says:

    Thanks man!
    Works nice

  5. Ryan Says:

    Thanks for the post. You’ve made a very nice modification.

    One problem I ran into was not being able to use multiple autocomplete components in the same form. As soon as you would complete one combo box and then begin typing in another the first combo box would only display the _typedText data and not the label of the selected item. This can be addressed by adding the following line to the focusOutHandler method

    _typedText = textInput.text

  6. sectore Says:

    Ryan,

    have you used the same data as the dataProvider for all components? In this case the component changes it while typing a text and all other components, which use the same data, will are affected.

    -Jens

  7. Marcus Says:

    Thanks!

  8. Marcus Says:

    Servus Jens,

    I have installed the AutoComplete. But there is one problem. The “prompt” property is not working for the AutoComplete Component.

    The text “bitte eingeben oder auswählen” should be in the textfield like the normal Combobox.

    Any idea?

  9. Marcus Says:

    Ok I found the solution! Can I send you the new code, that you maybe update the component?

  10. Jeff Says:

    I’m having an error while using your component. I added a change event to the control and I’m trying to grab the value of the selectedItem, however it’s producing errors.

    It seems that the following code does not work:

    public function ChangeEvent(evt:Event):void
    {
    variable=e.currentTarget.SelectedItem.name;
    }

    I’m trying to store the value of the selected item’s name field of the array into a variable.. but Flex doesn’t seem to be able to access that field.

    Am I doing something wrong?

  11. PeZ Says:

    Thanks but there is still an issue about your solution.

    Try clicking outside the combobox when it’s opened and the first value will be selected…which is not normal wanted behavior.

  12. Dirk Says:

    Thank’s for your solution, i hassle around with this component for weeks now.

    @PeZ this is the normal behaviour of a ComboBox it selects the current selected item and not the first one.

    My problem is to set the value of the field via the text property. To use the text property is probably wrong. I thought to use the typedText method but Flex complains about an unreachable method. The problem is, if you use text it is cleared after the close event is triggered.

    Currently i added this check to the close method:

    if(selectedIndex == 0 && selectedLabel != “”)

    …maybe there is a better way of doing that?

  13. Unknown Blog » Blog Archive » Flex AutoComplete Komponente für FLEX 3 Says:

    [...] wurde hat unter Flex 2 wunderbar funktioniert, jedoch sollte sich mit Flex 3 ein gewisses Fehlverhalten einschleichen. Für ein Flex 3 Projekt wollte ich diese Komponente einsetzen und hatte bisher mit [...]

  14. Yaison Says:

    I have found an issue in this component.

    try this:

    when the user press enter after typing the default button’s click event does not dispatches.

    thanks anyways, its a very usefull component.

  15. test Says:

    how to integrate the auto complete component with flex 3

  16. Steven Rieger Says:

    Thank you so much for resolving this issue. I have been trying to find / fix this for several days now!!!

  17. Micheal Says:

    Great component, but I needed one more feature. I added a NotInList event, so that I could add entries to the dataprovider if they were not in the list. To do that, just add:

    if(dataProvider.length==0 && textInput.text!=”" && textInput.text!=null){
    dispatchEvent(new Event(“notInList”));
    }
    to the focusOutHandler event. and add the meta data for the event at the head of your component.

  18. Rico Says:

    Hi,

    Can you send (or post) me the solution for the “prompt” issue as well ?

    Thank’s

    rico

  19. prashant shelke Says:

    Here is solution for my last question:

    if(collection.length==0 || typedText==”"|| typedText==null)
    {
    typedText = “”;// New line added here.

    This will flush invalid input if it nots in dataProvider.

    Thanks.

  20. Trinity Says:

    Thanks for sharing! This worked nicely for the same issue I was having with the Flex 3 autocomplete.

  21. andrea Says:

    Hi,
    great patch, I was searching for it in these hours!

    @Markus
    Can you post your solution for the prompt problem?

    @Rico
    Maybe can you post it? :-)

    Thanks a lot!

  22. prashant shelke Says:

    This codeis for restricting invalid character to type from user.
    if(collection.length == 0)
    {
    typedText = typedText.substr(0, typedText.length – 1);
    cursorPosition = typedText.length;
    }
    else
    {
    typedText = “”;
    cursorPosition = 0;
    }

    I have got one problem, if user will type above normal speed there is need to serialized keyboard input.

    If anyone knows solution please let me know.
    Thanks.

  23. prashant shelke Says:

    To get rid from “prompt” problem, I have added one object {data: -1, label:”Select Country”} @ top of dataProvider & removed “prompt”. So on change we can check for (selectedItem.data == -1) to perform next action.

    Thanks.

  24. Ueli Kistler Says:

    Here’s a quick fix to “enable” the default button feature…

    Add this method to AutoComplete.as:

    override protected function focusInHandler(event:FocusEvent):void
    {
    super.focusInHandler(event);

    var fm:IFocusManager = focusManager;
    if (fm) {
    fm.defaultButtonEnabled = true;
    }
    }

    Cheers!

  25. andrea Says:

    @prashant
    Thank you for the prompt hint, I’ll try it!

  26. prashant shelke Says:

    Hi,

    I m facing on strange problem here, please see steps:
    1. Suppose there are three items in a dataProvider say
    [A], [AB], [ABC]. If I will type ‘A’ & then focus out then 1st item will get select but its not calling CHANGE event.

    I have observed that if [typed text = one of item label] then this issue is coming.

    Can anyone please suggest solution.
    Thanks.

  27. Hillel Coren Says:

    First off, great fix. I had the same problem (plus a couple of others) so I ended up deciding to write my own AutoComplete component.

    You can check it out at:
    http://hillelcoren.com/2008/11/10/flex-autocomplete-component-a-new-take-on-an-old-standard/

    Best,
    Hillel

  28. prashant shelke Says:

    Please see this link:

    http://kuwamoto.org/2006/05/11/example-code-updated-for-beta-3/

    May be useful!

    Thanks.

  29. Composant Flex - AutoCompletion sur un champ Texte (AutoComplete TextInput) - Adobe Flex Tutorial - Tutoriaux Flex Builder, MXML, ActionScript, AS3 Says:

    [...] Version de ce composant modifiée pour être compatible avec Flex 3 [...]

  30. Jacob Says:

    Thanks for the tip. I wouldn’t characterize Adobe’s solution as faulty though. Theirs allows for entries not in the list. With your solution, it isn’t possible.

    For instance, and forgive me because I know this isn’t possible, but if I had a country named “Berm” I couldn’t enter it in. It keeps forcing me to Bermuda. Bermuda is a nice place, but it just isn’t Berm.

    With Adobe’s solution, I can hit up/down and select Bermuda if I want it, or I can just enter Berm.

    Thanks again for the code.

  31. Kunal Says:

    Hi, really like the fix that you made here. I’m looking to try and make an AutoComplete class in AS3 (or Flex) that will auto-complete multiple terms. In the framework of your example, if I started typing ‘b’, selected the first term Bermuda, *and then* started typing ‘b’ or another letter, that the auto-complete would pop back up and try and complete that next term. Any thoughts that anyone has on how to do this (preferably through an existing component) would be fantastic, I appreciate the help!

    Regards,
    Kunal

  32. Multiple AutoComplete Input Controls in a single Flex Form - Kerkness.ca Says:

    [...] Krause has posted a modified version of the component which allows the user to press ENTER, TAB or click their mouse button to select [...]

  33. Flex: Enhanced search ComboBox at Stefan B.log Says:

    [...] websector.de [...]

  34. eire Says:

    great fix. Im trying to get the example working by populating the datagrid from a webservice call however each whenever i do this the text field always displays with the first result of the web service call even before i click in the text field. Im new to Flex but wondering if its something i can change with your implementation? thanks

  35. purandhar Says:

    hi i need to autocomplete componet for which i will feed the data provider dynamically based on the typed text. can u have solution for this?

  36. Tim Says:

    Is there a way of pre-selecting an item from the dataprovider. I am adding a new object to the dataprovider using a popUp titleWindow. However when returning the first object is always displayed. I have tried setting the text, typedText and selectedItem to no avail.

    Does anyone know how I can do this.

  37. andrea Says:

    changed code to this to be able to catch the change event. I needed to populate other controls according to what the user picked.

    if(selectedIndex == 0)
    {
    textInput.text = selectedLabel;
    textInput.setSelection(cursorPosition,
    textInput.text.length);
    dispatchEvent(new ListEvent(ListEvent.CHANGE));
    }

  38. SGS Says:

    I have one problem.

    I have two instances in my application of this components.

    Whe I found in one component, no problem.

    But whe i go to the next autocomplete, and i write a value, the other autocomplete change the value.

    I put diferents id, and diferents filter functions.

    Someone can help me please?

    Sorry for my english.

    kind regards.

  39. cd eire Says:

    great code, thanks. can you tell me how i can modify to only start the autocomplete after the user has typed three letters/vales?

  40. Making Yahoo’s AutoCompleteManager work with defaultButton | Nate's Code Vault Says:

    [...] an annoying flickering whenever a key is pressed. Plus there were a few issues with it that I found here (make sure to read all the comments). Plus, since it is not based on TextInput, there are a few [...]

  41. Ravi Says:

    awesome code. I just have one problem. I am compiling against Flash player 10.0.0 (i.e. In Flex builder, Properties –> the required flash player version is 10.0.0). when the user inputs ‘ab’ and presses enter button, neither the drop down closes nor the first value is selected.

    Any help appreciated.

  42. Jeffry Houser Says:

    Hi Everyone,

    I just came across this post and noticed a few people had questions I can help with. I’m the brains behnd Flextras.com a bunch of Interface Flex Components. If you’ll excuse me while I wear my marketing hat for a second:

    David asked how to populate the AutoComplete data from a database. The Flextras AutoCompleteComboBox supports that functionality.

    Set the AutoCompleteRemoteData property to true. http://www.flextras.com/AutoCompleteComboBox/docs/asdocs/com/flextras/autoCompleteComboBox/AutoCompleteComboBox.html#autoCompleteRemoteData .
    Start with an empty / null dataProvider and as the user starts to type, capture, and cancel the autoCompleteDataProviderFilterBegin event ( http://www.flextras.com/AutoCompleteComboBox/docs/asdocs/com/flextras/autoCompleteComboBox/AutoCompleteComboBox.html#event:autoCompleteDataProviderFilterBegin
    ). In the event handler start your remote procedure call to get the new data.

    We have an example in our developer edition download of this.

    Tim asked about pre-selecting a value in the AutoComplete. Our AutoCompletComboBox has a field named AutoCompleteResetIndex which will allow you to specify any start value.
    http://www.flextras.com/AutoCompleteComboBox/docs/asdocs/com/flextras/autoCompleteComboBox/AutoCompleteComboBox.html#autoCompleteResetIndex

  43. Brian Says:

    Sorry I’m ne to Flex so I’m not sure if this is a dumb question but are there instructions for setting this up?

  44. ilya Says:

    Nice fix! The only thing I would add these 2 lines so that change event works properly – in case someone using that.

    var e: Event = new Event(“change”); dispatchEvent(e);

  45. Andrés Says:

    Thank you very much!!!!

  46. Josh Says:

    Thanks a lot for this fix, great help.

  47. halflife_baby Says:

    can anyone let me know how to use Autocomplete TextInput
    to display in the delow manner.if we type ‘A’ it should display as,and only ‘Cricket’ should be selected, other fields should not be selected.
    Country
    Australia
    Capital
    Melbourne
    Game
    Cricket

  48. Satheesh Chakravarthi Says:

    Thanks for the fix, I found this bug when I was testing Adobe’s AutoComplete TextInput.

    Thanks again!

    With kind regards,
    Satheesh C.

  49. Carl Brydon Says:

    Hello,
    I have been able to use the modified component provided and it works nicely with one small exception. When I click on the drop-down arrow at the right of the input box, nothing happens. I was hoping it would show me the whole list I have.

    I hope someone can provide some guidance.

    Thanks,
    Carl

  50. Rimjim Says:

    Hey. didnt read all the replies, if someone already mentioned this problem, dont care about this one. So if “Berlin” is (the first index) in your list, there is no chance to search for “be”. it autocompletes with the first item in your list (this case “berlin”)… if you wanna fix it, go to:

    override protected function commitProperties():void

    and change

    else
    {
    showDropdown = true;
    selectedIndex = 0;
    }

    to

    else
    {
    showDropdown = true;
    selectedIndex = -1;
    }

    have a nice day
    tim

  51. Carl Brydon Says:

    Thanks for the suggestion Rimjim, but that didn’t change anything. I’d be staisfied if I could hide the drop-down arrow button and have my whole list show when someone clicks in the textbox. Does anyone have an idea how to do that?

    Thanks,
    Carl

  52. Carl Brydon Says:

    Turns out all I needed to do was use the open method on the combobox.

  53. flash harry Says:

    I’m using this as form input replacement to offer suggested (not enforced) input. I have a couple of issues.

    1) Any way to add maxChars to the text input, I need to set the limit on the number of letter entered, I have done this with a string validation but if you type after the max chars warning it nulls out the input.
    2) if you add a string validation you can no longer write to the text property it nulls out, you can still write to the typetext property but this opens the list and I have to call close after a 1 second timer.

    TIA
    flash

  54. ??? ?????? ???? » filter && autoComplete Says:

    [...] Input component http://hillelcoren.com/flex-autocomplete/ http://www.websector.de/blog/2008/04/30/quick-tip-avoid-issues-using-adobes-autocomplete-input-compo... http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&extid=1047291 [...]

  55. kevin Says:

    Awesome.

    Thank you.

  56. http://vispyanskiy.name/?p=66 Says:

    [...] «Quick tip: Avoid issues using Adobes AutoComplete Input component using Flex 3» [...]

  57. Rz Says:

    Hi,

    Do you have any version working with flex 4? or any other solution?

  58. joe Says:

    Hi,

    I am tring to use the labelFunction but i get this error :
    Implicit coercion of a value of type void to an unrelated type Function.

    this is my code :

    private function allOwners_resultHandler(event:ResultEvent):void{
    var owners:ArrayCollection = event.result as ArrayCollection;
    myComboBox.dataProvider = owners;
    myComboBox.labelFunction = “ownerName”;
    }

    private function ownerName(item:UserBean):String {
    return item.firstName + ” “+ item.lastName ;
    }

    Can anyone please suggest solution.
    Thanks.

  59. PALMEDIC Says:

    Thank you for this great solution.

    However I had to remove line 340 where it says:
    selectedIndex = 0;

    Or otherwise when the list is filtered to a level only one item meet the criteria no change event is fired when this item is selected, because you pre-selected it.

Leave a Reply

Follow sectore on Twitter