Autocomplete
Build a debounced typeahead that fetches suggestions from an API and displays a dropdown.
Build a debounced typeahead that fetches suggestions from an API and displays a dropdown.
const $input = $("#search"), $results = $("#suggestions");
let timer;
$input.on("input", function() {
const q = $(this).val().trim();
clearTimeout(timer);
if (q.length < 2) { $results.hide(); return; }
timer = setTimeout(() => {
$.getJSON(`/api/search?q=${encodeURIComponent(q)}`, items => {
$results.html(items.map(i => `<li class="suggestion" data-id="${i.id}">${i.name}</li>`).join("")).show();
});
}, 300);
});
$(document).on("click", ".suggestion", function() {
$input.val($(this).text()); $results.hide();
});
$(document).on("click", e => { if (!$(e.target).closest("#search-wrap").length) $results.hide(); });
Always close the dropdown when clicking outside — attach the handler to document, not the container.