Remote data
Debounced, aborted, cached and paged — the request count is shown as you type.
<form class="demo" onsubmit="event.preventDefault()">
<div class="demo-field">
<label class="demo-label" for="city">City <span class="demo-hint">· type two letters, then delete and type them again</span></label>
<input id="city" name="city">
</div>
<div class="demo-kv">
<div><span class="demo-hint">keystrokes</span><br><b id="typed">0</b></div>
<div><span class="demo-hint">requests sent</span><br><b id="calls">0</b></div>
</div>
</form>
import { createSelect } from 'https://devix.pk/cdn/oss/select@1.0.0/index.js';
const CITIES = ['Dubai', 'Abu Dhabi', 'Sharjah', 'Karachi', 'Lahore', 'Islamabad', 'Riyadh', 'Jeddah', 'Doha', 'Manama', 'Muscat', 'Kuwait City', 'Mumbai', 'Delhi', 'Dhaka', 'Colombo', 'Manila', 'London', 'Berlin', 'Bucharest'];
const count = (id) => (document.getElementById(id).textContent = String(Number(document.getElementById(id).textContent) + 1));
// Stands in for your API: 400ms of latency, and it can be cancelled.
const search = (query, signal) =>
new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve(CITIES.filter((city) => city.toLowerCase().includes(query.toLowerCase())).map((city) => ({ value: city, label: city }))), 400);
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(new DOMException('cancelled', 'AbortError'));
});
});
createSelect(document.getElementById('city'), {
name: 'city',
minChars: 2,
debounce: 200,
placeholder: 'Search cities',
// Requests only outnumber pauses, never keystrokes — and a repeated query is answered from cache.
onSearch: () => count('typed'),
load: (query, { signal }) => {
count('calls');
return search(query, signal);
},
strings: { empty: 'No city by that name' },
});
@import url('https://devix.pk/cdn/oss/select@1.0.0/select.min.css');