AutocompletePro
FormKit Pro Quick Installation Guide 🚀
The autocomplete input allows you to search through a list of options.
The options prop can accept three different formats of values:
- An array of objects with
valueandlabelkeys (see example above) - An array of strings
['A', 'B', 'C'] - An object literal with key-value pairs
{ a: 'A', b: 'B', c: 'C' } - A function that returns any of the above
If you assign options as an empty array, the input will be rendered in a disabled state.
Basic examples
Single-select
By default, the autocomplete input will render in single-select mode:
<script setup>import countries from './countries.js'</script><template> <FormKit type="form" #default="{ value }" :actions="false"> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" :options="countries" popover /> <pre wrap>{{ value }}</pre> </FormKit></template>Multi-select
By setting the multiple prop the autocomplete input will render in multi-select mode:
<script setup>import countries from './countries.js'</script><template> <FormKit type="form" #default="{ value }" :actions="false"> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" :options="countries" multiple popover /> <pre wrap>{{ value }}</pre> </FormKit></template>Notice in the example above that because the multiple prop is set, the value prop must be an array.
Filtering
The autocomplete input will filter options with its own internal search function. You can replace this search function by providing the filter prop a function of your own. Your function will receive two arguments, the option being iterated over and the current search value:
<FormKit type="autocomplete" name="autocomplete" label="Search for a country" :options="countries" placeholder="Example: United States" popover :filter=" (option, search) => option.label.toLowerCase().startsWith(search.toLowerCase()) "/>Dynamic options
Instead of passing a static list to the options prop, you can assign it to a function. Doing so is useful when you need to load options from an API or another source.
Search parameter
In this example, we'll assign the options prop the searchMovies function. By doing so, searchMovies will receive the context object as an argument. Within this context object is the search property, which is the current search value. To perform our search, we'll use the search value as the query parameter for our API request:
<script setup>// Search movie receives FormKit's context object// which we are destructuring to get the search value.async function searchMovies({ search }) { if (!search) return [] const res = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=1&include_adult=false` ) if (res.ok) { const data = await res.json() // Iterating over results to set the required // `label` and `value` keys. return data.results.map((result) => { return { label: result.title, value: result.id, } }) } // If the request fails, we return an empty array. return []}</script><template> <!--Setting the `options` prop to async function `loadHorrorMovies`--> <FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example: Shawshank Redemption" popover :options="searchMovies" /></template>Page and hasNextPage parameters
A likely scenario you'll encounter is needing to search through a paginated API. This can be done by referencing the same context object as before. Within this object, we can utilize the page and hasNextPage properties. The page property is the current page number, and the hasNextPage property is a function to be called when there are more pages to load:
<script setup>// Search movie receives FormKit's context object// which we are destructuring to get the search value,// the page, and the hasNextPage parameters.async function searchMovies({ search, page, hasNextPage }) { if (!search) return [] const res = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=${page}&include_adult=false` ) if (res.ok) { const data = await res.json() if (page !== data.total_pages) hasNextPage() return data.results.map((result) => { return { label: result.title, value: result.id, } }) } return []}</script><template> <FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example: Lord of the Rings" :options="searchMovies" popover /></template><style scoped>:deep(.formkit-option) { display: flex; align-items: center;}:deep(.formkit-option img) { width: 20%; margin-right: 20px;}:deep(.option-overview) { font-size: 12px;}</style>Option loader
Rehydrating values
FormKit's autocomplete input also provides an optionLoader prop that allows you to rehydrate values that are not in the options list. In this example, we'll provide the autocomplete an initial value (a movie ID), and assign the optionLoader to a function that will make a request to the API to get the movie:
<script setup>// Search movie receives FormKit's context object// which we are destructuring to get the search value,// the page, and the hasNextPage parameters.async function searchMovies({ search, page, hasNextPage }) { if (!search) return [] const res = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=${page}&include_adult=false` ) if (res.ok) { const data = await res.json() if (page !== data.total_pages) hasNextPage() return data.results.map((result) => { return { label: result.title, value: result.id, } }) } return []}// The function assigned to the `option-loader` prop will be called with the// value of the option as the first argument (in this case, the movie ID), and// the cached option as the second argument (if it exists).async function loadMovie(id, cachedOption) { if (cachedOption) return cachedOption const res = await fetch( `https://api.themoviedb.org/3/movie/${id}?api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US` ) if (res.ok) { const data = await res.json() return { label: data.title, value: data.id, } } return { label: 'Error loading' }}</script><template> <FormKit type="form" #default="{ value }" :actions="false"> <FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example: Harry Potter" :options="searchMovies" :value="597" :option-loader="loadMovie" popover /> <pre wrap>{{ value }}</pre> </FormKit></template>e<style scoped>:deep(.formkit-option) { display: flex; align-items: center;}:deep(.formkit-option img) { width: 20%; margin-right: 20px;}:deep(.option-overview) { font-size: 12px;}</style>Notice in the example above that the optionLoader function is passed two arguments: the value of the selected option (in this case, the movie ID) and the cachedOption. The cachedOption prop is used for preventing unnecessary lookups. If the cachedOption is not null it means that the selected option has already been loaded, and you can return the cachedOption directly.
Loading Style
Instead of requiring your users to click the Load more button to load additional options, you can set the loadOnScroll prop to true, which will paginate options as you scroll to the bottom of the options list.
Load on created
If you would rather load options when the autocomplete is created, you can set the load-on-created prop to true, and our function, loadCurrentlyPopularMovies will be called without the user needing to expand the listbox:
<script setup>// Search movie receives FormKit's context object// which we are destructuring to get the search value.async function searchMovies({ search }) { await new Promise((resolve) => setTimeout(resolve, 1000)) if (!search) // With no search value, lets just return a list of common movies. return [ { label: 'Saving Private Ryan', value: 857 }, { label: 'Everything Everywhere All at Once', value: 545611 }, { label: 'Gone with the Wind', value: 770 }, ] const res = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=1&include_adult=false` ) if (res.ok) { const data = await res.json() // Iterating over results to set the required // `label` and `value` keys. return data.results.map((result) => { return { label: result.title, value: result.id, } }) } // If the request fails, we return an empty array. return []}</script><template> <FormKit type="form" #default="{ value }" :actions="false"> <!--Setting the `options` prop to async function `loadHorrorMovies`--> <FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example: Shawshank Redemption" :options="searchMovies" load-on-created popover /> <pre wrap>{{ value }}</pre> </FormKit></template><style scoped>:deep(.formkit-option) { display: flex; align-items: center;}:deep(.formkit-option img) { width: 20%; margin-right: 20px;}:deep(.option-overview) { font-size: 12px;}</style>Option appearance
Option slot
The autocomplete input allows you to customize the look and feel of each option by using the option slot. In this example, we are using the option slot to display each option's asset, logo, and name:
<script setup>import carBrands from './car-brands.js'</script><template> <FormKit type="autocomplete" name="autocomplete" label="Search for and select a car brand" placeholder="Example: Toyota" :options="carBrands" selection-appearance="option" popover > <!--OPTION SLOT--> <template #option="{ option, classes }"> <div :class="classes.option"> <img :src="option.logo" :alt="option.label + ' logo'" /> <span> {{ option.label }} </span> </div> </template> <!--/OPTION SLOT--> </FormKit></template><style scoped>.formkit-option { display: flex; align-items: center;}.formkit-option img { width: 20px; height: 20px; margin-right: 10px;}</style>Selection appearance
The autocomplete input allows you to customize the look and feel of the selected option.
Selection appearance prop
The autocomplete input allows you to customize the look and feel of the selected option by using the selection-appearance prop. For either the single-select or multi-select
autocomplete, you can set the selection-appearance prop to text-input (default) or option:
<script setup>import countries from './countries.js'</script><template> <FormKit type="autocomplete" label="Single-select text input" placheolder="Pick a country" :options="countries" popover value="FR" /> <FormKit type="autocomplete" label="Single-select option" placheolder="Pick a country" :options="countries" popover selection-appearance="option" value="FR" /> <FormKit type="autocomplete" label="Multiple text input" placheolder="Pick a country" :options="countries" popover multiple :value="['FR', 'GR', 'ES']" /> <FormKit type="autocomplete" label="Multiple option" placheolder="Pick a country" :options="countries" multiple selection-appearance="option" :value="['FR', 'GR', 'ES']" /></template>Selection slot
If you only want to customize the display of the selected option, set the selection appearance to option.
<FormKit type="autocomplete" name="autocomplete" label="Search and select a car brand" placeholder="Example: Toyota" :options="carBrands" popover selection-appearance="option" value="audi"> <!--SELECTION SLOT--> <template #selection="{ option, classes }"> <div :class="classes.selection"> <div :class="`${classes.option} flex items-center`"> <img :src="option.logo" :alt="option.label + ' logo'" class="w-10 h-10 p-2" /> <span> {{ option.label }} </span> </div> </div> </template> <!--/SELECTION SLOT--></FormKit><FormKit type="autocomplete" name="autocomplete" label="Search and select a car brand" placeholder="Example: Toyota" :options="carBrands" selection-appearance="option" multiple :value="['toyota', 'honda']"> <!--SELECTION SLOT--> <template #selection="{ option, classes }"> <div :class="`${classes.selection} !p-0`"> <div :class="`${classes.option} flex items-center`"> <img :src="option.logo" :alt="option.label + ' logo'" class="w-10 h-10 p-2" /> <span> {{ option.label }} </span> </div> </div> </template> <!--/SELECTION SLOT--></FormKit>
Audi
Toyota
HondaBehavioral props
Empty message
The autocomplete input, by default, will not expand the listbox when no search results are found while filtering. You can change this behavior by assigning the empty-message prop a message to display when no results are found:
<FormKit type="autocomplete" name="autocomplete" label="Search for a country" :options="countries" placeholder="Example: United States" empty-message="No countries found" popover/>Close on select
If you would like the listbox to remain expanded after selecting a value, you can set close-on-select to false.
<FormKit type="autocomplete" name="autocomplete" label="Search for a country" :options="countries" multiple :close-on-select="false" placeholder="Example: United States" popover/>Reload on commit
If you want the options to be reloaded when the user commits a selection, use the reload-on-commit prop:
<FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" :options="countries" :reload-on-commit="true" :close-on-select="false" multiple popover/>Open on click
To enable opening the autocomplete's listbox on click of its search input, set the open-on-click prop to true:
<FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" :options="countries" open-on-click popover/>Open on focus
If you would like to open the autocomplete's listbox anytime the input is clicked, set the open-on-focus prop to true:
<FormKit type="button" @click="focusAutocomplete"> Click me to focus autocomplete</FormKit><FormKit id="autocomplete" type="autocomplete" name="framework" label="Choose a frontend framework" placeholder="Example placeholder" :options="frameworks" open-on-focus popover/>If open-on-focus is used, open-on-click will implicitly be set.
Clear search on open
For single-select autocompletes only, if you would like to clear the search input when the listbox is opened, set the clear-search-on-open:
<script setup>import countries from './countries.js'</script><template> <FormKit type="form" #default="{ value }" :actions="false"> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" :options="countries" clear-search-on-open value="US" popover /> <pre wrap>{{ value }}</pre> </FormKit></template>Selection removable
For a single-select autocomplete, you can set the selection-removable prop. When set to true, a remove button will be displayed next to the selected option. This prop is by default set to true for autocompletes with selection appearance of option.
The selection-removable prop cannot be used for multi-selects.
<script setup>import countries from './countries.js'</script><template> <FormKit type="form" #default="{ value }" :actions="false"> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" :options="countries" value="US" popover selection-removable /> <pre wrap>{{ value }}</pre> </FormKit></template>Open on remove
If you want the listbox to expand when an selection is removed, use the open-on-remove prop:
<script setup>import countries from './countries.js'</script><template> <FormKit type="form" #default="{ value }" :actions="false"> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" :options="countries" open-on-remove selection-removable popover value="US" /> <pre wrap>{{ value }}</pre> </FormKit></template>Max
If you would like to limit the number of options that can be selected, you can use the max prop:
<script setup>import countries from './countries.js'</script><template> <FormKit type="autocomplete" label="Autocomplete (option appearance) with max prop set to 2" :options="countries" selection-appearance="option" multiple popover max="2" /> <FormKit type="autocomplete" label="Autocomplete (text-input appearance) with max prop set to 2" :options="countries" selection-appearance="text-input" multiple popover max="2" /></template>Full example
Now let's combine what we've learned so far by leveraging the option slot for custom markup, and setting the options prop to a function that will return pages of movies from an API:
<script setup>import topMovies from './top-movies.js'// Search movie receives FormKit's context object// which we are destructuring to get the search value,// the page, and the hasNextPage parameters.async function searchMovies({ search, page, hasNextPage }) { if (!search) { // When there is no search value we return a static list of top movies return topMovies } const res = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=${page}&include_adult=false` ) if (res.ok) { const data = await res.json() if (page !== data.total_pages) hasNextPage() return data.results.map((result) => { return { label: result.title, value: result.id, poster_path: result.poster_path, overview: result.overview, } }) } return []}</script><template> <FormKit type="form" #default="{ value }" :actions="false"> <FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example placeholder" :options="searchMovies" selection-appearance="option" multiple popover remove-selection-class="p-2 pl-0" > <template #option="{ option }"> <div class="flex items-center justify-between"> <div class="image-container w-1/4 mr-2"> <img :src="`https://image.tmdb.org/t/p/w500${option.poster_path}`" alt="optionAvatar" class="w-full" /> </div> <div class="text-container w-full"> <div class="text-base leading-none font-bold"> {{ option.label }} </div> <p class="option-overview text-xs"> {{ option.overview }} </p> </div> </div> </template> </FormKit> <pre wrap>{{ value }}</pre> </FormKit></template>Props & Attributes
| Prop | Type | Default | Description |
|---|---|---|---|
debounce | number | 200 | Number of milliseconds to debounce calls to an options function. |
options | any | [] | The list of options the user can select from. |
load-on-scroll | boolean | false | When set to true, the autocomplete will try loading more options based on the end-user`s scroll position |
selection-appearance | string | text-input | Changes the way the option label is display. |
multiple | boolean | false | Allows for multiple selections. |
open-on-click | boolean | false | The autocomplete is expanded upon focus of the input, as opposed to waiting to expand until a search value is entered. |
filter | function | null | Used to apply your own custom filter function for static options. |
option-loader | function | null | Used for hydrating initial value, or performing an additional request to load more information of a selected option. |
empty-message | string | undefined | Renders a message when there are no options to display. |
max | number | undefined | Limits the number of options that can be selected. |
open-on-remove | boolean | false | When the selection-removable prop is set to true, the autocomplete will not open after the selected value is removed. You can change this behavior by setting the open-on-remove prop to true. |
open-on-focus | boolean | false | |
options-appearance | string | undefined | For multi-select autocompletes, this prop allows you to customize the look and feel of the selected options. Possible values are default (the default) or checkbox. |
always-load-on-open | boolean | true | Determines whether the autocomplete should always load its options when opened or whether it should reference the options that were previously found when opening. |
load-on-created | boolean | false | When set to true, the autocomplete will load the options when the node is created. |
clear-search-on-open | boolean | false | When set to true, the search input will be cleared when the listbox is opened. |
max | number | string | undefined | If you would like to limit the number of options that can be selected, you can use the max prop (applies only to multi-select). |
popover | boolean | false | Renders the input's listbox using the browser Popover API. |
| Show Universal props | |||
config | Object | {} | Configuration options to provide to the input’s node and any descendent node of this input. |
delay | Number | 20 | Number of milliseconds to debounce an input’s value before the commit hook is dispatched. |
dirtyBehavior | string | touched | Determines how the "dirty" flag of this input is set. Can be set to touched or compare — touched (the default) is more performant, but will not detect when the form is once again matching its initial state. |
errors | Array | [] | Array of strings to show as error messages on this field. |
help | String | '' | Text for help text associated with the input. |
id | String | input_{n} | The unique id of the input. Providing an id also allows the input’s node to be globally accessed. |
ignore | Boolean | false | Prevents an input from being included in any parent (group, list, form etc). Useful when using inputs for UI instead of actual values. |
index | Number | undefined | Allows an input to be inserted at the given index if the parent is a list. If the input’s value is undefined, it inherits the value from that index position. If it has a value it inserts it into the lists’s values at the given index. |
label | String | '' | Text for the label element associated with the input. |
name | String | input_{n} | The name of the input as identified in the data object. This should be unique within a group of fields. |
parent | FormKitNode | contextual | By default the parent is a wrapping group, list or form — but this props allows explicit assignment of the parent node. |
prefix-icon | String | '' | Specifies an icon to put in the prefixIcon section. |
preserve | Boolean | false | Preserves the value of the input on a parent group, list, or form when the input unmounts. |
preserve-errors | Boolean | false | By default errors set on inputs using setErrors are automatically cleared on input, setting this prop to true maintains the error until it is explicitly cleared. |
sections-schema | Object | {} | An object of section keys and schema partial values, where each schema partial is applied to the respective section. |
suffix-icon | String | '' | Specifies an icon to put in the suffixIcon section. |
type | String | text | The type of input to render from the library. |
validation | String, Array | [] | The validation rules to be applied to the input. |
validation-visibility | String | blur | Determines when to show an input's failing validation rules. Valid values are blur, dirty, and live. |
validation-label | String | {label prop} | Determines what label to use in validation error messages, by default it uses the label prop if available, otherwise it uses the name prop. |
validation-rules | Object | {} | Additional custom validation rules to make available to the validation prop. |
value | Any | undefined | Seeds the initial value of an input and/or its children. Not reactive. Can seed entire groups (forms) and lists.. |
Sections & slot data
You can target a specific section of an input using that section's "key", allowing you to modify that section's classes, HTML (via :sections-schema, or content (via slots)). Read more about sections here.
The autocomplete's structure changes depending on a few different scenarios:
- Whether
selection-appearancehas been set totext-input(the default) oroption. - Whether multiple selections are enabled via the
multipleattribute.
Selection appearance text-input
When selection-appearance="text-input" (the default), the selected value(s) appear as comma-separated text in the input field.
Click on a section to lock focus to the chosen section. Click locked section again to unlock.
Selection appearance option
When selection-appearance="option", the selected value(s) render as styled chips. For single-select, the selections section appears inside inner. For multi-select, it appears inside wrapper below inner.
Click on a section to lock focus to the chosen section. Click locked section again to unlock.
Listbox (dropdown) structure
The listbox section contains the dropdown options. It is rendered inside a dropdownWrapper that handles positioning.
Click on a section to lock focus to the chosen section. Click locked section again to unlock.
| Section-key | Description |
|---|---|
selector | The selector section is a button element that opens the dropdown options list. |
selections | Contains individual selection sections. |
selection | Contains the selected option. |
listitem | A list item element that contains the option section. |
option | A div that contains the option content. |
listbox | The listbox section is a ul element that contains the options list. |
dropdownWrapper | Wraps the listbox section. A div that handles scrolling the listbox. |
optionLoading | A span element that is conditionally rendered within the selected option when loading is occurring. |
loaderIcon | An element for outputting an icon in the selector element when loading is occurring. |
selectIcon | An element for outputting an icon in the selector element when the dropdown is closed. |
loadMore | A list item element that is conditionally rendered at the bottom of the options list when there are more pages to load. |
loadMoreInner | A span element that acts as a wrapper for the loaderIcon within the loadMore section. |
removeSelection | A button element used for removing a specific selection. |
closeIcon | An element for outputting an icon within the removeSelection button. |
listboxButton | A button element that is used to open the dropdown. |
emptyMessage | A list item element that is conditionally rendered when there are no options to display. |
emptyMessageInner | A span element that acts as a wrapper for the emptyMessage section. |
| Show Universal section keys | |
outer | The outermost wrapping element. |
wrapper | A wrapper around the label and input. |
label | The label of the input. |
prefix | Has no output by default, but allows content directly before an input element. |
prefixIcon | An element for outputting an icon before the prefix section. |
inner | A wrapper around the actual input element. |
suffix | Has no output by default, but allows content directly after an input element. |
suffixIcon | An element for outputting an icon after the suffix section. |
input | The input element itself. |
help | The element containing help text. |
messages | A wrapper around all the messages. |
message | The element (or many elements) containing a message — most often validation and error messages. |
Accessibility
All FormKit inputs are designed with the following accessibility considerations in mind. Help us continually improve accessibility for all by filing accessibility issues here:
- Semantic markup
- ARIA attributes
- Keyboard accessibility
- Focus indicators
- Color contrast with the provided theme
- Accessible labels, help text, and errors
Accessibility attributes
| Section Key | Attribute | Value | Description |
|---|---|---|---|
input | tabindex | -1 or 0 | Prioritizes keyboard focus order by setting it to -1 when disabled and 0 when enabled. |
role | combobox | Indicates to assistive technologies that this element functions as a combobox. | |
readonly | Restrict user edits, ensuring data integrity and a controlled, informative user experience. | ||
aria-autocomplete | list | Guides input suggestions, presenting a collection of values that could complete the user's input. | |
aria-activedescendant | Manage focus to the current active descendent element. | ||
aria-expanded | Conveys the expandable state when the element is in focus. | ||
aria-controls | Associates the listbox element, with this element. | ||
listboxButton | tabindex | -1 or 0 | Prioritizes keyboard focus order by setting it to -1 when disabled and 0 when enabled. |
role | button | Indicates to assistive technologies that this element functions as a button. | |
aria-haspopup | true | Signals that an element triggers a pop-up or menu | |
aria-expanded | Conveys the expandable state when the element is in focus. | ||
aria-controls | Associates the listbox element, with this element. | ||
aria-disabled | Communicates the disabled state when the input is disabled. | ||
selectionWrapper | tabindex | -1 or 0 | Prioritizes keyboard focus order by setting it to -1 when disabled and 0 when enabled. |
selections | aria-live | polite | Communicates dynamic content changes when selections are on the screen. |
removeSelection | tabindex | -1 | Removes the prioritization of keyboard focus on this element. |
aria-controls | Associates the input element, with this element. | ||
| Universal Accessibility Attributes | |||
label | label | for | Associates a label to an input element. Users can click on the label to focus the input or to toggle between states. |
input | input | disabled | Disables an HTML element, preventing user interaction and signaling a non-interactive state. |
aria-describedby | Associates an element with a description, aiding screen readers. | ||
aria-required | Added when input validation is set to required. | ||
icon | icon | for | Links icon to input element when icon in rendered as a label. |
Keyboard Interactions
| Keyboard Event | Description |
|---|---|
| Enter | Opens the listbox when the input is focused. Selects an item when a list item is focused |
| Space | Opens the listbox when the input is focused. Selects an item when a list item is focused |
| Esc | Closes the listbox when the input is focused. |
| ↑ | Navigates to previous list item in list box. Closes listbox if most-previous item is selected |
| ↓ | Opens the listbox when input is focused. Navigates to next list item in list box. |
| Universal Keyboard Events | |
| Tab | Moves the focus to the next focusable element on the page. |
| Shift+Tab | Moves the focus to the previous focusable element on the page. |