jqueryjsontypeahead.jsbootstrap-typeaheadbloodhound

Typahead Bloodhound hint and autocomplete not working with remote url


I don't know why its not working with remote url. Its working fine when same results/json array loaded locally.

My code

 var bh_engine = new Bloodhound({
                datumTokenizer: function(d) {


                    var my_string = d.company_name;
                    my_string = my_string.replace(/\s/g, "");
                    var string_length = my_string.length;

                    var my_matches = [];

                    for (var i = 0; i < string_length; i++) {
                        my_matches.push(my_string.substring(i, string_length));
                    }

                    return my_matches;
                },
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                local: local_source,
                prefetch: prefetch_source,
                remote: remote_source
            });

         bh_engine.initialize();


            $(apply_on_element + ' .bootstrap-tags-input input#mytaginput').typeahead({
                hint: true,
                highlight: true,
                minLength: 1
            }, {
                async:true,
                displayKey: 'company_name',
                source: bh_engine.ttAdapter()


            });

Json data

[{"company_name":"Google","code":1},{"company_name":"Facebook","code":2}]

Tested with same data locally and remote. Its giving problems only with remote access.

Any idea? why?

You can also check here JSfiddle

First type "string1" or "string2" and so on string...

and then with remote data Type "data30" and so on.....

It shows first element of json object every time

As you can see bold/highlight feature working fine, but hint not

I want to show only "data50" when i enter "data50" or at least on first place in the list


Solution

  • You can use Bloodhound transform method on the remote object to simulate the same behaviour that's implemented for the local data.

    window.bh = bloodhoundSuggestions = new Bloodhound({
          datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          sufficient: 3,
          local: suggestions,
          remote: {
              url: 'https://www.mockaroo.com/api/generate.json?key=9c13bbb0&schema=typeahead',
              transform: function(response) {
    
                // input selector
                var input = $("#tagsInput").val();
                  return response.filter( function (item) {
                    return input.toLowerCase() == item.value.toLowerCase().substr(0, input.length);
                });
             }
          },
      });
    

    JsFiddle - just type in data