Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter your jquery autocomplete data while typing

So far I have the following

var aCleanData = ['aaa','aab','faa','fff','ffb','fgh','mmm','maa'];

$('#my-input').autocomplete({
    source:aCleanData,
    minLength:2
});

Currently if you type aa, aaa,aab,faa,maa will show.

What I would like to do is when the user types ff the data that is shown will be the fff,ffb data.

Basically, only what is typed should be matched from the first character onwards.

This should be recursive. When user types fg, fff,ffb should disapear and only fgh should appear.

Thanks in advance for your help.

UPDATE:

p.s. See what I mean here:

http://jqueryui.com/demos/autocomplete/#default

Type sc and you'll see more than just the data beginning with sc.

like image 626
HGPB Avatar asked Dec 06 '22 18:12

HGPB


1 Answers

One possible solution to get only results starting with the input value is to check the array elements before search by yourself:

var aCleanData = ['aaa','aab','faa','fff','ffb','fgh','mmm','maa'];
$('#my-input').autocomplete({
    source: aCleanData,
    minLength: 2,
    search: function(oEvent, oUi) {
        // get current input value
        var sValue = $(oEvent.target).val();
        // init new search array
        var aSearch = [];
        // for each element in the main array ...
        $(aCleanData).each(function(iIndex, sElement) {
            // ... if element starts with input value ...
            if (sElement.substr(0, sValue.length) == sValue) {
                // ... add element
                aSearch.push(sElement);
            }
        });
        // change search array
        $(this).autocomplete('option', 'source', aSearch);
    }
});

Also see my jsfiddle.

like image 150
scessor Avatar answered Dec 10 '22 12:12

scessor