0

I found this code online that gives options for autocomplete and I would like to give the options which start the key in letters. For example, if the alphabet 'a' is keyed in, I just want to give options start with 'a' not the options contain 'a', so from the code, when I key in 'a', I only want to display apple, not pineapples. How can I do that?

var x = [
{ label : 'apple', value : 'Delicious' },
{ label : 'pineapples', value : 'Delicious' },
{ label : 'kiwi', value : 'Yummy' },
{ label : 'kiwiooo', value : 'aaa' },
{ label : 'lemon', value : 'Sour' }
];

$( "#fruit" ).autocomplete({
source: x,
focus : function(){ return false; }}).on( 'autocompleteselect',           
function( e, ui ){
var t = $(this),
details = $('#taste'),
label = ( e.type == 'autocompleteresponse' ? ui.content[0].label :      
ui.item.label ),
value = ( e.type == 'autocompleteresponse' ? ui.content[0].value : 
ui.item.value );
t.val( label );
details.val( value );
return false;});

1 Answers1

0

The solution is pretty easy. I found the filter method used just for that. All that needs to be done is replacing that function with this:

// Overrides the default autocomplete filter function to and find only from the beginning of the string
<script>
$("#fruit").autocomplete({ source: function(request, response) {
  var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
  response($.grep(myArray, function(item){
     return matcher.test(item);
  }));
 }
});
</script>

There is another solution which i have used before.

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