Autocomplete
Suggest matching values as users type, with single or multiple selection.
Basic example
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.
<div class="input-field outlined">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autocomplete-input" class="autocomplete" placeholder=" " />
<label for="autocomplete-input">Autocomplete</label>
<span class="supporting-text">Select a single item</span>
</div>Setup
Start with the kmaterialize CSS and JavaScript from Getting started, then follow the component setup below.
Initialize after the input exists. Supply a list of suggestions; each option needs an id and may include display text.
import { Autocomplete } from 'kmaterialize';
Autocomplete.init(document.querySelector('#autocomplete-input'), {
minLength: 0,
data: [
{ id: 12, text: 'Apple' },
{ id: 13, text: 'Microsoft' }
]
});Examples and variants
Multiple selections
Use isMultiSelect: true for multiple selections. Selected values appear as removable chips; the input stays available for searching, and the menu remains open while you choose more items.
<!-- Single selection: the selected label fills the input. -->
<div class="input-field outlined">
<input type="text" id="autocomplete-input" class="autocomplete" placeholder=" ">
<label for="autocomplete-input">Autocomplete</label>
</div>
<!-- Multiple selections: initialize this input with isMultiSelect: true. -->
<div class="input-field">
<input type="text" id="autocomplete-input-multi" class="autocomplete-multiple" placeholder=" ">
<label for="autocomplete-input-multi">Multiple Autocomplete</label>
</div>Custom search
document.addEventListener('DOMContentLoaded', function() {
const elems = document.querySelectorAll('.autocomplete');
const instances = 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 Multi Select
document.addEventListener('DOMContentLoaded', function() {
const elems = document.querySelectorAll('.autocomplete-multiple');
const instances = 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 Multi Select and custom search function
document.addEventListener('DOMContentLoaded', function() {
const elems = document.querySelectorAll('.autocomplete-multiple');
const instances = 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);
}
});
});
Validation
Autocomplete suggestions do not make a field required or restrict it to listed values. Use required and validate membership in your application when a suggested value must be selected.
These previews keep their error state visible. In your form, show errors after checking a field or submitting, then clear them when the value is valid.
For text fields, use .input-field.error, aria-invalid="true", and a message linked with aria-describedby. Remove the error state when resolved. Use aria-live="polite" for messages updated dynamically.
Required
Unknown value
<div class="input-field outlined error">
<i class="material-icons suffix" aria-hidden="true">error</i>
<input id="validation-autocomplete" type="text" class="autocomplete" required placeholder=" " value="" aria-invalid="true" aria-describedby="validation-autocomplete-error">
<label for="validation-autocomplete">Recipient</label>
<span id="validation-autocomplete-error" class="supporting-text">Choose a recipient.</span>
</div>
<div class="input-field error">
<i class="material-icons suffix" aria-hidden="true">error</i>
<input id="validation-autocomplete-choice" type="text" class="autocomplete" placeholder=" " value="Unknown person" aria-invalid="true" aria-describedby="validation-autocomplete-choice-error">
<label for="validation-autocomplete-choice">Recipient</label>
<span id="validation-autocomplete-choice-error" class="supporting-text">Choose a recipient from the suggestions.</span>
</div>Reference
Suggestion data
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.
ATTENTION: Data-Format has changed from version 1.X.X to 2.0.0! Please update option 'data'.
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.
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:
const instance = 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. |