简体   繁体   中英

JavaScript YUI Autocomplete Source change

I'm using YUI for an auto completion and I need the data for the auto completion to change dynamically.

For example I have an input box which says "user name" and it will autocomplete according to function(userName) which would return an array accordingly.

How do I implement that?

One way to do this is to define the source of the AutoComplete as a function:

new Y.AutoComplete({
    // your code here ...
    source: getSource
});

In that function you can return a dynamically modified array of results:

function getSource() {
    if (something) {
        return [ 'something' ];
    }
    else {
        return [ 'somethingElse' ];
    }
}

Here's a runnable example: (click the button to change the completion array)

 YUI().use('autocomplete', function(Y) { var reversed = false; function getSource() { if (!reversed) { return ['foo', 'bar', 'baz']; } else { return ['oof', 'rab', 'zab']; } } new Y.AutoComplete({ inputNode: Y.one('#input'), render: true, source: getSource }); Y.one('#button').on('click', function(event) { reversed = !reversed; }); }); 
 <script src="https://cdn.rawgit.com/stiemannkj1/0214fdc4cccaa77d6e504320cf70a571/raw/63d260364730fb067f103c00862c7e65685256df/yui-3.18.1_build_yui_yui-min.js"></script> <input id="input" /> <button id="button">Reverse</button> 

Note: You can use the sendRequest() method to programmatically requery the source. This can be useful if you've changed the list and want to show the new list before the user types anything new.

For more information on dynamic sources for AutoComplete , check out the "Result Sources" section of the YUI AutoComplete Article/Documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM