'Run AlgoliaSearch Autocomplete if query text is greater than 3-4 characters

I am trying to limit AlgoliaSearch to show results for Autocomplete only if the uer types more than 3-4 charchters in the input box, I have tried using keypress event in jquery to do this but unfortunately that does not work, I tried searching Algolia blogs but to no avail. Below is my code,

var initvalues = initvariables;
    var url = userdetails['webroot'];
    console.log(initvalues);
    console.log(url);
    var fileName = '';
    if (url.includes('qa')|| url.includes('dev') || url.includes('localhost')) {
        fileName = "constants-dev.json";
    } else if(url.includes('pp')|| url.includes('pre-prod')) {
        fileName = "constants-preprod.json";
    } else {
        fileName = "constants-prod.json";
    }

    var directory = window.location.pathname.split('/')[1];

    var json = $.getJSON({'url': location.protocol + '//' + location.host +'/'+  directory +  '/blocks/algoliasearch/'+ fileName, 'async': false});
    json = JSON.parse(json.responseText);
    console.log(json);

    var client = algoliasearch(json.appId, json.apiKey);
    
    var clientIndex = json.current_index;
    var index = client.initIndex(clientIndex);
    console.log("Index" + JSON.stringify(index));
    console.log(autocomplete.sources.hits(index, this.userFilters(userdetails)))
    if (document.getElementsByTagName('html')[0].getAttribute('lang') == 'en' || document.getElementsByTagName('html')[0].getAttribute('xml:lang') == 'en') {
        var myAutoComplete = autocomplete('#searchform_search', { hint: false }, [
            {
                source: autocomplete.sources.hits(index, this.userFilters(userdetails)),
                displayKey: 'title.en',
                templates: {
                    suggestion: function (suggestion) {
                        var sugTemplate = '';
                        if (suggestion.modalite.en == 'Online') {
                            sugTemplate += '<span class="ena-aamodalonline"></span>';
                        } else if (suggestion.modalite.en == 'In Person') {
                            sugTemplate += '<span class="ena-aamodalinperson"></span>';
                        } else {
                            sugTemplate += '<span class="ena-aamodalhybrid"></span>';
                        }

                        //sugTemplate += '<img src="">'; // Where course's images would be displayed
                        sugTemplate += '<a class="ena-aaresult" href="'+url+'/course/view.php?id='+suggestion.courseid+'">'+suggestion.title.en+'</a>';
                        /*if (suggestion.partageable == 'Locale') {
                            sugTemplate += '<span class="ena-aalocal">Local</span>';
                        } else {
                            sugTemplate += '<span class="ena-aapart">Shareable</span>';
                        }
                        sugTemplate += '<span class="ena-aaest">'+suggestion.establishmentfullname+'</span>';*/
                        //sugTemplate += '<hr/>';
                        return sugTemplate;
                    }
                }
            }
        ]).on('autocomplete:selected', function (event, suggestion, dataset) {
            console.log(suggestion);
            console.log(dataset)
            window.location.href = url+'/course/view.php?id='+suggestion.courseid;
        });



    } else {
        var myAutoComplete = autocomplete('#searchform_search', { hint: false }, [
            {
                source: autocomplete.sources.hits(index, this.userFilters(userdetails)),
                displayKey: 'title.fr',
                templates: {
                    suggestion: function (suggestion) {
                        var sugTemplate = '';
                        if (suggestion.modalite.en == 'Online') {
                            sugTemplate += '<span class="ena-aamodalonline"></span>';
                        } else if (suggestion.modalite.en == 'In Person') {
                            sugTemplate += '<span class="ena-aamodalinperson"></span>';
                        } else {
                            sugTemplate += '<span class="ena-aamodalhybrid"></span>';
                        }

                        //sugTemplate += '<img src="">'; // Where course's images would be displayed
                        sugTemplate += '<a class="ena-aaresult" href="'+url+'/course/view.php?id='+suggestion.courseid+'">'+suggestion.title.fr+'</a>';
                        /*if (suggestion.partageable == 'Locale') {
                            sugTemplate += '<span class="ena-aalocal">'+suggestion.partageable+'</span>';
                        } else {
                            sugTemplate += '<span class="ena-aapart">'+suggestion.partageable+'</span>';
                        }
                        sugTemplate += '<span class="ena-aaest">'+suggestion.establishmentfullname+'</span>';*/

                        //sugTemplate += '<hr/>';
                        return sugTemplate;
                    }
                }
            }
        ]).on('autocomplete:selected', function (event, suggestion, dataset) {
            //alert($('#algoliasearchinput.value') + "  " + JSON.stringify($('#algoliasearchinput.value')));
            window.location.href = url+'/course/view.php?id='+suggestion.courseid;
        });
    }
 
}

I am unable to parse the query as the function expects the selector as parameter, how can I modify it so as the autocomplete only run when input searchform_search only has more 3 characters in it.

Below is the Codepen for a working prototype: https://codepen.io/karankia/pen/eYyGQbE



Solution 1:[1]

Found the solution on Algolia Automcomplete.js documentation on Github here: https://github.com/algolia/autocomplete/blob/45fa32d008620cf52bf4a90530be338543dfba7f/README.md#global-options. The solution is to recreate the source property in order to obtain the typed query.

 var hitsSource =  autocomplete.sources.hits(index, this.userFilters(userdetails));
        var myAutoComplete = autocomplete('#searchform_search', { hint: false }, [

            {
                source: function(query, callback) {
                    if (query.length > 2) {
                        hitsSource(query, function(suggestions) {
                            callback(suggestions);
                        });
                    }

                },
                displayKey: 'title.en',
                templates: '' 
             }
            ]);

Solution 2:[2]

Looks like you got there. It's also documented here with conditional sources similar to: https://www.algolia.com/doc/ui-libraries/autocomplete/guides/changing-behavior-based-on-query/#adding-conditional-sources

but with the same query.length > 2

I'd be remiss if I didn't mention this is considered an anti-pattern for most autocomplete use cases. A surprising number of results can be found with less than three characters with good ranking criteria.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karan
Solution 2 Chuck Meyer