views:

57

answers:

1

I'm using the jQuery UI Autocomplete with a local datasource (source: myArray). I want the autocomplete to propose only the results that start with the string entered instead of the default case-insensitive contains search. Is there a simple solution for this or do I have to provide my custom search/source callback?

+1  A: 

Currently I've done it this way, not sure if there is a better solution:

source: function(request, response) {
    var filteredArray = $.map(orignalArray, function(item) {
        if( item.value.startsWith(request.term)){
            return item;
        }
        else{
            return null;
        }
    });
    response(filteredArray);
},

This approach also made it possible to impose a limit (e.g. 10 items) on the amount of items to be shown.

Bart
I am by no means an expert on these things but can imagine a string matching algorithm like Aho–Corasick can help.
Huppie
Before you misunderstand my previous comment. Implementing string matching yourselves should only be done when performance is absolutely critical AND a profiler shows you your current solution is the bottleneck. Until then, use the solution you have now. Readability of your code trumps the performance benefits in this case :)
Huppie
Your proposal about the string matching algorithm also means a custom callback method like mine above (if I'm not wrong). It might be interesting in some particular cases like you say, even though the UI Autocomplete already implements a decent search (with contains).For now I'll stick with my implementation (I only got 3k items of 4chars each).
Bart
I'll accept my own answer since I'm not getting alternatives.
Bart