autocomplete

Add ajax multiple autocomplete to textarea

In this article we will show a solution to add an ajax call to populate multiple information in a Drupal 8 form textarea element.

In this example, the script will autocomplete users list in the form for a custom module called MyModule. The user will enter first 2 letters of a name or email.

1) create a library

In MyModule.libraries.yml add the necessary javascript reference that will be used to populate the users in the form:

MyModule_lib:
  version: VERSION
  js:
    js/autocomplete.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui.autocomplete

The autocomplete function as dependencies which are based on jQuery library.

 

2) JS script

The jQuery autocomplete.js file that we use is copied below. It is implemented as Drupal behaviors You need to add this file in MyModule/js/ folder.
 

JS script: