Search now shows nothing if nothing was found

This commit is contained in:
david 2023-05-20 12:58:17 +02:00
parent 2defe8a4bd
commit 1759b09aec

View File

@ -1,38 +1,38 @@
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);
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 < 1) {clearSuggestions(searchsuggestions)}
else {
if (s.length > 0) {
try {
const response = await fetch("/api/search/?q=" + s);
const result = await response.json();
setSuggestions(searchsuggestions, result);
return result;
} catch(error) {
console.log("Error: " + error);
}
}
return [];
}
function clearSuggestions(o) {
function nothing() {
const span = document.createElement("span");
span.setAttribute("class", "dropdown-item-text");
span.insertAdjacentText("afterbegin", "Nothing");
const li = document.createElement("li");
li.appendChild(span);
o.replaceChildren(li);
return li(span);
}
function setSuggestions(o, s) {
const newSuggestions = [];
for (const vid of s) {
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);
const li = document.createElement("li");
li.appendChild(a);
newSuggestions.push(li);
items.push(li(a));
}
o.replaceChildren(...newSuggestions);
return items;
}