
Features:
- Supports both single-select and multi-select modes.
- Fetches dynamic data from external APIs via custom asynchronous functions.
- Case-sensitive and case-insensitive search.
- Minimum character threshold.
- Full keyboard navigation via Arrow keys, Enter, Escape, and Backspace.
- Clear control in either button or icon style.
- Displays selected items as removable tags above or inside the input field.
- Works perfectly with Bootstrap utility classes and components.
- Built-in debouncing to optimize API calls during fast typing.
How To Use It:
1. Add the AvalynxAutocomplete stylesheet and script to your Bootstrap project.
<!-- Bootstrap is required --> <link rel="stylesheet" href="/path/to/cdn/bootstrap.min.css" /> <script src="/path/to/cdn/bootstrap.bundle.min.js"></script> <!-- AvalynxAutocomplete --> <link rel="stylesheet" href="/dist/css/avalynx-autocomplete.css"> <script src="/dist/js/avalynx-autocomplete.js"></script>
2. Or install & import AvalynxAutocomplete with NPM.
# NPM $ npm install avalynx-autocomplete
import { AvalynxAutocomplete } from 'avalynx-autocomplete';3. Add a standard text input to your markup.
<!-- Target input field --> <input type="text" id="citySearch">
4. Initialize AvalynxAutocomplete and define your own data in a JS array:
const cityAC = new AvalynxAutocomplete('#citySearch', {
data: [
{ key: 'nyc', value: 'New York' },
{ key: 'la', value: 'Los Angeles' },
{ key: 'chi', value: 'Chicago' },
{ key: 'hou', value: 'Houston' },
{ key: 'phx', value: 'Phoenix' }
],
maxItems: 5, // Show at most 5 results in the dropdown
minLength: 2 // Start searching only after 2 characters
}, {
placeholder: 'Type a city name...',
noResults: 'No cities matched your search'
});5. Pass an async fetchData function when your data comes from an API endpoint. The function receives the current query string and must return a { key, value } array.
// Autocomplete powered by a remote product search endpoint
const productAC = new AvalynxAutocomplete('#productSearch', {
fetchData: async (query) => {
// query is the current trimmed input value
const response = await fetch(`/api/products?q=${encodeURIComponent(query)}`);
const json = await response.json();
// Map the API response shape to the required { key, value } format
return json.items.map(item => ({ key: String(item.id), value: item.title }));
},
minLength: 3, // Require at least 3 characters before hitting the API
debounce: 400 // Wait 400ms after the last keystroke before running the fetch
});6. Set maxSelections to any value greater than 1 to activate multi-select mode. The component renders each selection as a removable badge tag.
<input type="text" id="langPicker">
const langAC = new AvalynxAutocomplete('#langPicker', {
data: [
{ key: 'js', value: 'JavaScript' },
{ key: 'ts', value: 'TypeScript' },
{ key: 'py', value: 'Python' },
{ key: 'rb', value: 'Ruby' },
{ key: 'go', value: 'Go' }
],
maxSelections: 3, // Allow up to 3 simultaneous selections
tagsPosition: 'inline', // Render badge tags inside the input container
clearStyle: 'icon', // Use an × icon control rather than a button
onChange: (keys, selections) => {
// keys: flat array of selected key strings
// selections: array of { key, value } objects
console.log('Selected keys:', keys);
console.log('Full selection objects:', selections);
}
});7. Set pre-selected values on init.
// Pre-populate a single-select field with a value loaded from the database
const countryAC = new AvalynxAutocomplete('#countryPicker', {
data: [
{ key: 'us', value: 'United States' },
{ key: 'de', value: 'Germany' },
{ key: 'fr', value: 'France' }
],
defaultKey: 'de', // Key of the item to select on load
defaultValue: 'Germany' // Visible label for that item
});
// Pre-populate a multi-select field with multiple saved values
const tagAC = new AvalynxAutocomplete('#tagPicker', {
data: [
{ key: 'js', value: 'JavaScript' },
{ key: 'ts', value: 'TypeScript' },
{ key: 'py', value: 'Python' }
],
maxSelections: 5,
defaultSelections: [
// Each object must include both key and value
{ key: 'js', value: 'JavaScript' },
{ key: 'ts', value: 'TypeScript' }
]
});8. All default configuration options.
className(string): Additional CSS class names appended to the dropdown<ul>element. Default:''.maxItems(number): Maximum number of results displayed in the dropdown at one time. Default:5.maxSelections(number): Maximum number of items the user can select. Any value greater than1activates multi-select mode. Default:1.minLength(number): Minimum number of characters the user must type before a search runs. Default:1.debounce(number): Milliseconds to wait after the last keystroke before executing the search. Default:300.caseSensitive(boolean): Whentrue, the static data filter matches character case exactly. Default:false.disabled(boolean): Initializes the component in a disabled state when set totrue. Default:false.defaultValue(string | null): Visible label of the pre-selected item on initialization. Default:null.defaultKey(string | null): Key of the pre-selected item on initialization. Default:null.defaultSelections(array | null): Array of{ key, value }objects used to pre-populate a multi-select field on initialization. Default:null.tagsPosition(string): Controls where multi-select badge tags render. Accepts'above'or'inline'. Default:'above'.clearStyle(string): Controls the appearance of the clear control. Accepts'button'or'icon'. Default:'button'.data(array | null): Static array of{ key, value }objects used as the search source. Default:null.fetchData(function | null): Async function that receives the query string and returns a{ key, value }array. Default:null.onChange(function | null): Callback fired when the selection changes. Receives the selected key(s) and the full selection object(s). Default:null.onClear(function | null): Callback fired when the user clears the field. Default:null.onLoaded(function | null): Callback fired after the component finishes initializing all matched elements. Default:null.
const cityAC = new AvalynxAutocomplete('#citySearch', {
className: '',
maxItems: 5,
maxSelections: 1,
minLength: 1,
debounce: 300,
caseSensitive: false,
disabled: false,
defaultValue: null,
defaultKey: null,
defaultSelections: null,
tagsPosition: 'above', // 'above' | 'inline'
clearStyle: 'button', // 'button' | 'icon'
data: null,
fetchData: null,
onChange: null,
onClear: null,
onLoaded: null,
}9. Language Options:
const cityAC = new AvalynxAutocomplete('#citySearch', {
// options here
}, {
placeholder: 'Search...',
noResults: 'No results found',
clearTitle: 'Clear selection',
removeTitle: 'Remove',
});10. API methods:
// Disable all input instances managed by this AvalynxAutocomplete object
autocomplete.disable();
// Re-enable all input instances
autocomplete.enable();
// Clear all current selections and reset the input fields
autocomplete.clear();
// Read the current value of a single-select instance
// Returns: { key: string, value: string }
const current = autocomplete.value;
console.log(current[0].key); // e.g. 'de'
console.log(current[0].value); // e.g. 'Germany'
// Read all selected items from a multi-select instance
// Returns: array of arrays of { key, value } objects (one array per matched element)
const allSelections = autocomplete.value;
// Read only the selected key(s)
// Single-select returns: string
// Multi-select returns: array of strings
const selectedKey = autocomplete.key;
console.log(selectedKey); // e.g. 'de' or ['js', 'ts']
// Set a value programmatically on a single-select instance
// Pass an array with one { key, value } object per matched element
autocomplete.value = [{ key: 'fr', value: 'France' }];
// Set multiple values on a multi-select instance
// The outer array corresponds to matched elements; the inner array holds selections
autocomplete.value = [
[{ key: 'js', value: 'JavaScript' }, { key: 'py', value: 'Python' }]
];Alternatives:
The post Bootstrap 5 Autocomplete Component In Vanilla JS – AvalynxAutocomplete appeared first on CSS Script.
Discover more from RSS Feeds Cloud
Subscribe to get the latest posts sent to your email.
