Tibby Tibby - 2 months ago 24
jQuery Question

jQuery autocomplete (devbridge) search from beginning

I am using devbridge's autocomplete jQuery script.
Is there an option to filter the search from the beginning of the word and not to apply to anywhere in a word?

Like if I would type "R" then I would like to see only the words starting with R and not the R character in every word.

Basicly a search from beginning kind of filter is what I am looking for.

How could this be done? Is there an option for this?

<script>
$(function() {

var fruits = [
{ value: 'Apple', data: 'Apple' },
{ value: 'Pear', data: 'Pear' },
{ value: 'Carrot', data: 'Carrot' },
{ value: 'Cherry', data: 'Cherry' },
{ value: 'Banana', data: 'Banana' },
{ value: 'Radish', data: 'Radish' }
];

$("#autocomplete").autocomplete({
lookup: fruits,
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
});
});
</script>

Answer

Add lookupFilter function:

$("#autocomplete").autocomplete({
    lookup: fruits,
    onSelect: function (suggestion) {
      alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
    },
    lookupFilter: function (suggestion, query, queryLowerCase) {
        return suggestion.value.toLowerCase().indexOf(queryLowerCase) === 0;
    }
});