I have implemented autocomplete in my application and using azure search for suggestion. But currently it's giving suggestion if the matches found in between line. But I want to search it begin with of given term like if I type What is then it should

  • what is first name
  • what is second name
  • what is third name

but currently its returning like

  • By the way what is
  • what is first name
  • what is second name

Please see below code which I am using

$("#autocomplete").autocomplete({
                    source: "/home/suggest?username=myname&",
                    minLength: 3                   
                });


$.ui.autocomplete.filter = function (source, term) {
            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
            return $.grep(source, function (value) {
                return matcher.test(value.label || value.value || value);
            });
        };

1 Answers

0
blgt On Best Solutions

When you set source to a string, autocomplete doesn't use its internal filter function. To do post-request filtering, handle the request yourself:

source: function( request, response ) {
    var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );

    if ( this.xhr ) {
        this.xhr.abort();
    }

    this.xhr = $.ajax( {
        url: "/home/suggest",
        data: $.extend({username:"myname"}, request),
        dataType: "json",
        success: function( data ) {
            response(
                $.grep( data, function( value ) {
                    return matcher.test( value.label || value.value || value );
                } )
            );
        },
        error: function() {
            response( [] );
        }
    } );
}

Explanation:

filter isn't part of the widget's API. You should not overwrite the library's internal functions without very good reason.

Instead, manually handle post-filtering with the source option. The second parameter response provides a callback for any result you want to pass to the widget. Handle the AJAX call manually and then process the result before passing it back to response. See here for an explanation of how source works.

Disclaimer:

This is bad practice. Filtering is done first on the server, by term, then on the client, by the ^ matcher. It sends unnecessary data over the network. It should be done at a single point. Either pre-load all data to the client, or just let the server handle the filtering.

Only use this if you both have no access to the server code and cannot pre-load.