Autocomplete
Implement an autocomplete input using jQuery's AJAX to fetch suggestions as the user types, then show results in a dropdown.
Implement an autocomplete input using jQuery's AJAX to fetch suggestions as the user types, then show results in a dropdown.
$("#search").on("input", function() {
const q = $(this).val().trim();
if (q.length < 2) { $("#suggestions").empty(); return; }
$.getJSON("/api/suggest?q=" + encodeURIComponent(q), function(items) {
const html = items.map(item =>
`<li class="list-group-item list-group-item-action suggestion"
data-id="${item.id}">${item.name}</li>`
).join("");
$("#suggestions").html(html);
});
});
$(document).on("click", ".suggestion", function() {
$("#search").val($(this).text());
$("#suggestions").empty();
});
Debounce the input event to avoid firing AJAX on every keystroke.