0

I am trying to adapt this terrific script / functionality from GoRails from a few years ago, to a Rails 7 application (which uses jsbundler-rails for javascript processing). https://gorails.com/episodes/global-autocomplete-search?autoplay=1

easy-autocomplete seems to be registered properly; if in the console I type something like

options = { data: ["one", "two", "three"]};
$('.autocomplete').easyAutocomplete(options);

The functionality works as expected.

However, using the script - adaption is shown below as I tried to migrate from turbolinks to turbo - I always end up with this error as soon as I start to type anything into the search-form:

jquery.easy-autocomplete.js:661 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at reduceElementsInList (jquery.easy-autocomplete.js:661:62)
    at proccessData (jquery.easy-autocomplete.js:614:10)
    at ListBuilderService.processData (jquery.easy-autocomplete.js:455:27)
    at Object.<anonymous> (jquery.easy-autocomplete.js:1377:45)
    at fire (jquery.js:3500:31)
    at Object.fireWith [as resolveWith] (jquery.js:3630:7)
    at done (jquery.js:9796:14)
    at XMLHttpRequest.<anonymous> (jquery.js:10057:9)

Here's the adjusted script:

import easyAutocomplete from "easy-autocomplete";

document.addEventListener("turbo:load", function () {
  var $input = $('.autocomplete');
  var options = {
    getValue: "name",
    url: function (phrase) {
      return "/search.json?q=" + phrase;
    },
    categories: [
      {
        listLocation: "books",
        header: "<strong>Books</strong>",
      },
      {
        listLocation: "authors",
        header: "<strong>Authors</strong>",
      },
    ],
    list: {
      onChooseEvent: function () {
        var url = $input.getSelectedItemData().url;
        $input.val("");
        turbo.visit(url);
      },
    },
    theme: "yellow",
  };
  $input.easyAutocomplete(options);
});

...which is loaded in application.js as follows (last line - as you can see, other scripts are importet too):

import "@hotwired/turbo-rails";
import "./controllers"
import "trix";
import "@rails/actiontext";
// custom jquery setup
import "./jquery";
// selectize setup
import "./selectize";
// noty for notifications
import "./noty";
// search for the autocomplete-search
import "./search";

Any ideas what could be wrong?

tkhobbes
  • 368
  • 3
  • 16

0 Answers0