41 lines
1.4 KiB
JavaScript
41 lines
1.4 KiB
JavaScript
function searchsuggestions() {
|
|
const searchinput = document.querySelector("#search");
|
|
const searchsuggestions = document.querySelector("#searchdropdown");
|
|
const li = (c) => document.createElement("li").appendChild(c);
|
|
searchinput.addEventListener("input", (e) => {
|
|
q(e.target.value).then((d) => {
|
|
if (d.length < 1) searchsuggestions.replaceChildren(nothing());
|
|
else searchsuggestions.replaceChildren(...suggestions(d));
|
|
})
|
|
});
|
|
async function q(s) {
|
|
if (s.length > 0) {
|
|
try {
|
|
const response = await fetch("/api/search/?q=" + s);
|
|
const result = await response.json();
|
|
return result;
|
|
} catch(error) {
|
|
console.log("Error: " + error);
|
|
}
|
|
}
|
|
return [];
|
|
}
|
|
function nothing() {
|
|
const span = document.createElement("span");
|
|
span.setAttribute("class", "dropdown-item-text");
|
|
span.insertAdjacentText("afterbegin", "Nothing");
|
|
return li(span);
|
|
}
|
|
function suggestions(d) {
|
|
const items = [];
|
|
for (const vid of d) {
|
|
const a = document.createElement("a");
|
|
a.setAttribute("class", "dropdown-item")
|
|
a.setAttribute("href", "/view/" + vid.id);
|
|
a.insertAdjacentText("afterbegin", vid.name + " " + vid.id);
|
|
items.push(li(a));
|
|
}
|
|
return items;
|
|
}
|
|
}
|
|
searchsuggestions(); |