Search code examples
javascriptautocompleteliferayalloy-ui

Autocomplete item selection in Alloy UI


I am working with Alloy UI auto-complete plugin that comes with Liferay. My auto complete part is working completely fine.

Now, what I want to do is that I want to capture the data which is selected from the auto complete auto suggest, and do the operation.

Let say, if I write ry in auto complete and then list comes up like this :

ryan
rynda
ryab

Now, if I click on any item or select via keyboard arrow key and press enter, it gets copied to autocomplete source input box. But I want is that I want to return back and do nothing when user selects a particular one item lets say ryab.

I found the event

autocomplete.on('itemSelect',function(event) {
};

which is fired when I select any item, but I don't know how to get the object which is selected and how to return false/do nothing by comparing the object.

Any help would be appreciated!


Solution

  • The following code should do the trick:

    var expandit = false;
    
    autocomplete.on('itemSelect', function(event) {
        var currentValue = autocomplete.inputNode.get('value');
        //do comparison logic with currentValue here, and eventually set input node value to empty string
        if (currentValue == 'foo') {
            expandit = true;
            autocomplete.inputNode.set('value', '');
            // stop event propagation
            event.stopImmediatePropagation();
            return false;
        }
    });
    
    autocomplete.on('containerCollapse', function(event) {
        //reopen the menu in case of "do nothing" selection
        if (expandit) {
            autocomplete._sendQuery(autocomplete.inputNode.get('value') + '*');
            expandit = false;
        }
    });
    

    Alloy UI Reference API and Source Code for the Autocomplete widget have been useful.


    To programmatically show the menu you can use:

    autocomplete._sendQuery(autocomplete.inputNode.get('value') + '*');