Autocomplete
A text input that suggests values as you type, from the page or from your server, and still accepts any text.
Installation
bash
npx bootcn add autocompletebash
pnpm dlx bootcn add autocompletebash
yarn dlx bootcn add autocompletebash
bunx --bun bootcn add autocompleteThe CLI also installs the design tokens and these components: label. It prints the <link> and <script> tags to add to your layout.
Usage
Use Autocomplete when any text is allowed and suggestions only help (cities, tags, search). When the value must be one of the options, use Combobox instead.
A PHP endpoint for remote suggestions:
php
<?php
header('Content-Type: application/json');
$q = mb_strtolower($_GET['q'] ?? '');
$matches = array_values(array_filter($cities, fn ($c) => str_contains(mb_strtolower($c), $q)));
echo json_encode(array_slice($matches, 0, 20));JavaScript API
data-bootcn-autocompleteon the wrapper, an<input role="combobox" aria-autocomplete="list">and arole="listbox"list ofrole="option"items (optionaldata-value; the text is the label).- Typing filters the suggestions (case-insensitive, anywhere in the label) and marks the match. ↓/↑ move through them, Enter picks one, Escape closes the list and then clears the input, Alt + ↓ opens it.
- The input keeps any text: it is a normal text field for the form.
- Remote suggestions:
data-bootcn-autocomplete-url="/cities.php?q="on the wrapper. The query is appended (encoded) 200 ms after typing stops; the response is a JSON array of strings or{ value, label }objects. Older requests are cancelled. - Event
bootcn:autocomplete:select(bubbles),detail: { value, label }; the input also fireschange. Bootcn.autocomplete.close(root);init()/destroy().
Accessibility
- Follows the WAI-ARIA combobox pattern with list autocomplete: the input owns the listbox (
aria-controls),aria-expandedfollows the list andaria-activedescendantpoints to the highlighted suggestion. - The number of suggestions is announced in a live region.
- Matches are marked with
<mark>and bold text, not colour alone.
Dependencies
- Bootstrap 5.3+ CSS.
themes/tokens/tokens.css.- The
labelcomponent.
Source
The exact files the CLI installs (autocomplete@1.0.1). View on GitHub · Report an issue
html
<div class="bootcn-autocomplete" data-bootcn-autocomplete>
<label class="bootcn-label" id="bootcn-autocomplete-city-label" for="bootcn-autocomplete-city"
>City</label
>
<input
class="form-control bootcn-autocomplete__input"
id="bootcn-autocomplete-city"
name="city"
type="text"
role="combobox"
aria-autocomplete="list"
aria-expanded="false"
aria-controls="bootcn-autocomplete-city-list"
aria-describedby="bootcn-autocomplete-city-help"
autocomplete="off"
placeholder="Start typing a city…"
/>
<p class="bootcn-autocomplete__help" id="bootcn-autocomplete-city-help">
Choose a suggestion or type any city.
</p>
<ul
class="bootcn-autocomplete__list"
id="bootcn-autocomplete-city-list"
role="listbox"
aria-labelledby="bootcn-autocomplete-city-label"
hidden
>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-amsterdam"
role="option"
aria-selected="false"
>
Amsterdam
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-athens"
role="option"
aria-selected="false"
>
Athens
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-barcelona"
role="option"
aria-selected="false"
>
Barcelona
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-berlin"
role="option"
aria-selected="false"
>
Berlin
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-brussels"
role="option"
aria-selected="false"
>
Brussels
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-copenhagen"
role="option"
aria-selected="false"
>
Copenhagen
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-dublin"
role="option"
aria-selected="false"
>
Dublin
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-lisbon"
role="option"
aria-selected="false"
>
Lisbon
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-london"
role="option"
aria-selected="false"
>
London
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-madrid"
role="option"
aria-selected="false"
>
Madrid
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-milan"
role="option"
aria-selected="false"
>
Milan
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-paris"
role="option"
aria-selected="false"
>
Paris
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-prague"
role="option"
aria-selected="false"
>
Prague
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-rome"
role="option"
aria-selected="false"
>
Rome
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-stockholm"
role="option"
aria-selected="false"
>
Stockholm
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-thessaloniki"
role="option"
aria-selected="false"
>
Thessaloniki
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-vienna"
role="option"
aria-selected="false"
>
Vienna
</li>
<li
class="bootcn-autocomplete__option"
id="bootcn-autocomplete-city-warsaw"
role="option"
aria-selected="false"
>
Warsaw
</li>
</ul>
<p class="visually-hidden" role="status" data-bootcn-autocomplete-status></p>
</div>css
.bootcn-autocomplete {
position: relative;
display: flex;
flex-direction: column;
gap: 0.5rem;
width: 20rem;
max-width: 100%;
}
.bootcn-autocomplete__input {
height: var(--bootcn-control-height);
padding: var(--bootcn-control-padding-y) var(--bootcn-control-padding-x);
border-color: var(--bootcn-input);
border-radius: var(--bootcn-radius);
background-color: transparent;
box-shadow: var(--bootcn-shadow-sm);
color: var(--bootcn-foreground);
}
.bootcn-autocomplete__input:focus {
border-color: var(--bootcn-ring);
background-color: transparent;
box-shadow: 0 0 0 3px var(--bs-focus-ring-color);
color: var(--bootcn-foreground);
}
.bootcn-autocomplete__input::placeholder {
color: var(--bootcn-muted-foreground);
}
@media (min-width: 768px) {
.bootcn-autocomplete__input {
font-size: var(--bootcn-control-font-size);
}
}
.bootcn-autocomplete__help {
margin: 0;
color: var(--bootcn-muted-foreground);
font-size: 0.875rem;
}
.bootcn-autocomplete__list {
position: absolute;
z-index: 1000;
top: calc(1.25rem + var(--bootcn-control-height) + 0.75rem);
inset-inline-end: 0;
inset-inline-start: 0;
max-height: 15rem;
margin: 0;
padding: 0.25rem;
overflow-y: auto;
border: var(--bootcn-border-width) solid var(--bootcn-border-color);
border-radius: var(--bootcn-radius);
background-color: var(--bootcn-background);
box-shadow: var(--bootcn-shadow-md);
font-size: 0.875rem;
list-style: none;
}
.bootcn-autocomplete__list[hidden],
.bootcn-autocomplete__option[hidden] {
display: none;
}
.bootcn-autocomplete__option {
padding: 0.375rem 0.5rem;
border-radius: var(--bootcn-radius-sm);
cursor: default;
}
.bootcn-autocomplete__option:hover,
.bootcn-autocomplete__option[aria-selected='true'] {
background-color: var(--bootcn-accent);
color: var(--bootcn-accent-foreground);
}
.bootcn-autocomplete__option mark {
padding: 0;
background: transparent;
color: inherit;
font-weight: 600;
}js
(function () {
'use strict';
const ns = (window.Bootcn = window.Bootcn || {});
if (ns.autocomplete) return; // already loaded: idempotent
const ROOT = '[data-bootcn-autocomplete]';
const OPTION = '[role="option"]';
const state = new WeakMap(); // root -> { timer, controller }
let listening = false;
function parts(root) {
return {
input: root.querySelector('[role="combobox"]'),
list: root.querySelector('[role="listbox"]'),
status: root.querySelector('[data-bootcn-autocomplete-status]'),
};
}
function stateOf(root) {
if (!state.has(root)) state.set(root, {});
return state.get(root);
}
function labelOf(option) {
if (!option.hasAttribute('data-label'))
option.setAttribute('data-label', option.textContent.trim());
return option.getAttribute('data-label');
}
function valueOf(option) {
return option.getAttribute('data-value') || labelOf(option);
}
function visible(root) {
return Array.from(parts(root).list.querySelectorAll(OPTION)).filter(function (option) {
return !option.hidden;
});
}
// The matched part in <mark>, built from text nodes (never parsed as HTML).
function highlight(option, query) {
const label = labelOf(option);
const at = query ? label.toLowerCase().indexOf(query) : -1;
option.replaceChildren();
if (at < 0) {
option.textContent = label;
return;
}
const mark = document.createElement('mark');
mark.textContent = label.slice(at, at + query.length);
option.append(label.slice(0, at), mark, label.slice(at + query.length));
}
function announce(root, text) {
const status = parts(root).status;
if (status) status.textContent = text;
}
function setActive(root, option) {
const p = parts(root);
p.list.querySelectorAll(OPTION).forEach(function (other) {
other.setAttribute('aria-selected', String(other === option));
});
if (option) {
p.input.setAttribute('aria-activedescendant', option.id);
option.scrollIntoView({ block: 'nearest' });
} else {
p.input.removeAttribute('aria-activedescendant');
}
}
function open(root) {
const p = parts(root);
if (visible(root).length === 0) return close(root);
p.list.hidden = false;
p.input.setAttribute('aria-expanded', 'true');
}
function close(root) {
const p = parts(root);
p.list.hidden = true;
p.input.setAttribute('aria-expanded', 'false');
setActive(root, null);
}
function filter(root) {
const p = parts(root);
const query = p.input.value.trim().toLowerCase();
let count = 0;
p.list.querySelectorAll(OPTION).forEach(function (option) {
const match = !query || labelOf(option).toLowerCase().includes(query);
option.hidden = !match;
highlight(option, match ? query : '');
if (match) count += 1;
});
setActive(root, null);
if (count) open(root);
else close(root);
announce(root, count === 1 ? '1 suggestion.' : count + ' suggestions.');
}
// Remote suggestions: data-bootcn-autocomplete-url + the encoded query
// returns a JSON array of strings or { value, label } objects.
function fetchRemote(root) {
const p = parts(root);
const url = root.getAttribute('data-bootcn-autocomplete-url');
const s = stateOf(root);
clearTimeout(s.timer);
if (s.controller) s.controller.abort();
const query = p.input.value.trim();
if (!query) {
p.list.replaceChildren();
close(root);
return;
}
s.timer = setTimeout(function () {
s.controller = new AbortController();
fetch(url + encodeURIComponent(query), { signal: s.controller.signal })
.then(function (response) {
return response.ok ? response.json() : [];
})
.then(function (items) {
p.list.replaceChildren();
(Array.isArray(items) ? items : []).slice(0, 50).forEach(function (item, index) {
const option = document.createElement('li');
option.className = 'bootcn-autocomplete__option';
option.id = p.list.id + '-' + index;
option.setAttribute('role', 'option');
option.setAttribute('aria-selected', 'false');
const label = typeof item === 'string' ? item : String(item.label || item.value);
option.setAttribute('data-label', label);
if (typeof item === 'object' && item.value !== undefined) {
option.setAttribute('data-value', String(item.value));
}
p.list.appendChild(option);
});
filter(root);
})
.catch(function () {
// Aborted or offline: keep the current list.
});
}, 200);
}
function choose(root, option) {
const p = parts(root);
p.input.value = valueOf(option);
close(root);
p.input.dispatchEvent(new Event('change', { bubbles: true }));
root.dispatchEvent(
new CustomEvent('bootcn:autocomplete:select', {
bubbles: true,
detail: { value: valueOf(option), label: labelOf(option) },
}),
);
}
function move(root, delta) {
const options = visible(root);
if (!options.length) return;
const p = parts(root);
const current = p.input.getAttribute('aria-activedescendant');
let index = options.findIndex(function (option) {
return option.id === current;
});
index =
index < 0
? delta > 0
? 0
: options.length - 1
: (index + delta + options.length) % options.length;
setActive(root, options[index]);
}
function onInput(event) {
const root = event.target.closest && event.target.closest(ROOT);
if (!root || event.target !== parts(root).input) return;
if (root.hasAttribute('data-bootcn-autocomplete-url')) fetchRemote(root);
else filter(root);
}
function onKeydown(event) {
const root = event.target.closest && event.target.closest(ROOT);
if (!root || event.target !== parts(root).input) return;
const p = parts(root);
const expanded = !p.list.hidden;
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
if (!expanded) {
filter(root);
if (event.altKey) return;
}
move(root, event.key === 'ArrowDown' ? 1 : -1);
} else if (event.key === 'Enter' && expanded) {
const active = p.input.getAttribute('aria-activedescendant');
const option = active && document.getElementById(active);
if (option) {
event.preventDefault();
choose(root, option);
} else {
close(root);
}
} else if (event.key === 'Escape') {
if (expanded) {
event.preventDefault();
close(root);
} else if (p.input.value) {
event.preventDefault();
p.input.value = '';
filter(root);
close(root);
}
} else if (event.key === 'Tab') {
close(root);
}
}
function onMousedown(event) {
const option = event.target.closest && event.target.closest(ROOT + ' ' + OPTION);
if (option) event.preventDefault(); // keep focus in the input
}
function onClick(event) {
const option = event.target.closest && event.target.closest(ROOT + ' ' + OPTION);
if (option) choose(option.closest(ROOT), option);
}
function onFocusOut(event) {
const root = event.target.closest && event.target.closest(ROOT);
if (root && !root.contains(event.relatedTarget)) close(root);
}
const handlers = [
['input', onInput],
['keydown', onKeydown],
['mousedown', onMousedown],
['click', onClick],
['focusout', onFocusOut],
];
function init() {
if (listening) return;
handlers.forEach(function (pair) {
document.addEventListener(pair[0], pair[1]);
});
listening = true;
}
function destroy() {
if (!listening) return;
handlers.forEach(function (pair) {
document.removeEventListener(pair[0], pair[1]);
});
listening = false;
}
ns.autocomplete = { init: init, destroy: destroy, close: close };
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
