Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RAILS 6 - how to use EasyAutocomplete

I try the last hours to integrate EasyAutocomplete into RAILS 6. But not so easy.

What I did :

Install Javascript Package with yarn:

# yarn add easy-autocomplete

Add this in the file app/javascript/packs/application.js

import “easy-autocomplete”

Add this in the file app/assets/stylesheets/application.css

*= require easy-autocomplete
*= require easy-autocomplete.themes

Then start the Rails Server and refresh the Web Page. Then try to use it. Go into the developer console and type :

var options = {
data: ["otto", "hans", "paula"] 
};

$("#task_name_search_field").easyAutocomplete(options);

task_name_search_field was previously defined as id :

<input type="search" class="form-control" id="task_name_search_field">

I got this message: TypeError: $(...).EasyAutocomplete is not a function

Any idea ?

like image 561
Sven Kirsten Avatar asked Oct 28 '25 08:10

Sven Kirsten


1 Answers

I had the same problem. Turbolinks does not give access to the script, the code needs to be run after it is loaded, something like this:

document.addEventListener("turbolinks:load", function() {
  var options = {
   data: ["otto", "hans", "paula"] 
  };

  $("#task_name_search_field").easyAutocomplete(options);
});

In order for the autocomplete to work, you need to add a script file to the application.js like this:

require("packs/youfile")

If it helps you, here is an example of my code:

document.addEventListener("turbolinks:load", function() {
 $input = $("[data-behavior='autocomplete']")

 var options = {
  getValue: "full_name",
  url: function(phrase) {
  return "/search.json?q=" + phrase;
 },
categories: [
  {
    listLocation: "cameras",
    header: "<strong>Cameras</strong>",
  }
],
list: {
  onChooseEvent: function() {
    var url = $input.getSelectedItemData().url
    $input.val("")
    Turbolinks.visit(url)
  }
 }
}
$input.easyAutocomplete(options)});
like image 74
Artem Shevchenko Avatar answered Oct 31 '25 01:10

Artem Shevchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!