Autocomplete

Materialize is a modern responsive CSS framework based on Material Design by Google.

Add an autocomplete dropdown below your input to suggest possible values in your form. You can populate the list of autocomplete options dynamically as well.

textsms Select a single item

You can initialize the Autocomplete with isMultiSelect for multiple selections

textsms

ATTENTION: Data-Format has changed from version 1.X.X to 2.0.0! Please update option 'data'.

          Copied!
          content_copy
          

<div class="row">
  <div class="col s12">
    <div class="row">
      <div class="input-field col s12">
        <i class="material-icons prefix">textsms</i>
        <input type="text" id="autocomplete-input" class="autocomplete">
        <label for="autocomplete-input">Autocomplete</label>
      </div>
    </div>
  </div>
</div>

          
        

Initialization

The data is an array of option objects, which supports three different attributes:

  • id: This is the only mandatory attribute: it must be a primitive value that can be converted to string. If "text" is not provided, it will also be used as "option text" as well;

  • text: This optional attribute is used as "display value" for the current entry. When provided, it will also be taken into consideration by the standard search function.

    If you trust your data or have properly sanitized your user input, you may use use HTML by setting the option allowUnsafeHTML: true;

  • image: This optional attribute is used to provide a valid image URL to the current option. This attribute is ignored by the standard search function.

You may also provide additional attributes to an option object but they will not be taken into consideration by the standard search function. If you want to use them for option filtering, you must specify a custom function in "onSearch" option.

            Copied!
            content_copy
            
  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      // specify options here
      minLength: 0, // shows instantly
      data: [
        {id: 12, text: "Apple"},
        {id: 13, text: "Microsoft"},
        {id: 42, text: "Google", image: 'http://placehold.it/250x250'}
      ]
    });
  });

  // With Mutlti Select

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      // specify options here
      minLength: 0, // shows instantly
      isMultiSelect: true,
      data: [
        {id: 12, text: "Apple"},
        {id: 13, text: "Microsoft"},
        {id: 42, text: "Google", image: 'http://placehold.it/250x250'}
      ]
    });
  });

  // With Mutlti Select and custom search function

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      // specify options here
      isMultiSelect: true,
      data: [
        {id: 12, text: "Apple"},
        {id: 13, text: "Microsoft"},
        {id: 42, text: "Google", image: 'http://placehold.it/250x250'}
      ],
      // This search function considers every object entry as "search values".
      onSearch: (text, autocomplete) => {
        const filteredData = autocomplete.options.data.filter(item => {
          return Object.keys(item)
            .map(key => item[key].toString().toLowerCase().indexOf(text.toLowerCase()) >= 0)
            .some(isMatch => isMatch);
        });
        autocomplete.setMenuItems(filteredData);
      }
    });
  });
          
        

Options

Name Type Default Description
data Array [] Array with Data-Objects defining autocomplete options with optional icon (image). The Property id is required which can be string or integer. It is also possible to use the properties text and image.
isMultiSelect boolean false Flag which can be set if multiple values can be selected. The Result will be an Array.
maxDropDownHeight string '300px' The height of the Menu which can be set via css-property.
onAutocomplete Function null Callback for when autocompleted. After a Selection was made this Function is called. This is also called when a default value is set.
onSearch Function(text, el)   Function is called when the input text is altered and data can also be loaded asynchronously. If the results are collected the items in the list can be updated via the function setMenuItems(collectedItems).
minLength Number 1 Minimum number of characters before autocomplete starts. When set to 0, the Options are shown on click or focus.
dropdownOptions Object {} Pass options object for the dropdown initialization.
allowUnsafeHTML Boolean false If true will render the key from each item directly as HTML. User input MUST be properly sanitized first.
onSearch

This is the default Search Function. You can write your own search function by passing in a function with the same parameters. You can load asynchronously data in this function or filter an existing list or dictionary. When the data is loaded you can use setMenuItems() to update the content of the Menu.

            Copied!
            content_copy
            
onSearch: (text, autocomplete) => {
  const normSearch = text.toLocaleLowerCase();
  autocomplete.setMenuItems(
    autocomplete.options.data.filter((option) => 
      option.id.toString().toLocaleLowerCase().includes(normSearch)
        || option.text?.toLocaleLowerCase().includes(normSearch)
    )
  );
}

          

To disable sorting and use the values as they appear in the data object, use a falsy value.

Methods

All the methods are called on the plugin instance. You can get the plugin instance like this:

              Copied!
              content_copy
              
  var instance = M.Autocomplete.getInstance(elem);
  instance.open();
              
            
.open();

Open autocomplete dropdown.


instance.open();
      
.close();

Close autocomplete dropdown.


instance.close();
      
.selectOption(id);

Select a specific autocomplete option via id-property.

Arguments

id: The id of a data-entry.


instance.selectOption(42);
      
.setMenuItems(items);

Updates the visible or selectable items shown in the menu.

Arguments

items: .


instance.setMenuItems([
  {id: "Test"},
  {id: 12, text: "Apple"},
  {id: 13, text: "Microsoft"},
  {id: 42, text: "Google", image: 'http://placehold.it/250x250'}
]);
      
.destroy();

Destroy plugin instance and teardown


instance.destroy();
      

Properties

Name Type Description
el Element The DOM element the plugin was initialized with.
options Object The options the instance was initialized with.
isOpen Boolean If the autocomplete is open.
count Number Number of matching autocomplete options.
activeIndex Integer Index of the current selected option.
dropdown Dropdown Instance of the dropdown plugin for this autocomplete.