66 lines
1.5 KiB
JavaScript
66 lines
1.5 KiB
JavaScript
import { Controller } from "@hotwired/stimulus"
|
|
|
|
export default class extends Controller {
|
|
static targets = ["input", "results", "item"]
|
|
|
|
connect() {
|
|
// Schließt die Liste, wenn man irgendwo außerhalb hinklickt
|
|
this.closeHandler = (e) => {
|
|
if (!this.element.contains(e.target)) {
|
|
this.hideResults()
|
|
}
|
|
}
|
|
document.addEventListener("click", this.closeHandler)
|
|
}
|
|
|
|
disconnect() {
|
|
document.removeEventListener("click", this.closeHandler)
|
|
}
|
|
|
|
// Wird aufgerufen, wenn der Nutzer tippt (input-Event)
|
|
filter() {
|
|
const filterValue = this.inputTarget.value.toLowerCase().trim()
|
|
|
|
if (filterValue === "") {
|
|
this.showAll()
|
|
return
|
|
}
|
|
|
|
this.showResults()
|
|
let hasMatches = false
|
|
|
|
this.itemTargets.forEach(item => {
|
|
const text = item.textContent.toLowerCase()
|
|
if (text.includes(filterValue)) {
|
|
item.classList.remove("hidden")
|
|
hasMatches = true
|
|
} else {
|
|
item.classList.add("hidden")
|
|
}
|
|
})
|
|
|
|
// Falls gar nichts gefunden wird, blenden wir die Liste aus
|
|
if (!hasMatches) this.hideResults()
|
|
}
|
|
|
|
// Ein Klick auf einen Eintrag wählt ihn aus
|
|
select(event) {
|
|
const value = event.currentTarget.dataset.value
|
|
this.inputTarget.value = value
|
|
this.hideResults()
|
|
}
|
|
|
|
showResults() {
|
|
this.resultsTarget.classList.remove("hidden")
|
|
}
|
|
|
|
hideResults() {
|
|
this.resultsTarget.classList.add("hidden")
|
|
}
|
|
|
|
showAll() {
|
|
this.showResults()
|
|
this.itemTargets.forEach(item => item.classList.remove("hidden"))
|
|
}
|
|
}
|