Files
vault171/app/javascript/controllers/autocomplete_controller.js
David Böhm 8c7482c1d7
Some checks failed
CI / scan_ruby (push) Has been cancelled
CI / scan_js (push) Has been cancelled
CI / lint (push) Has been cancelled
CI / test (push) Has been cancelled
CI / system-test (push) Has been cancelled
Changed item#_form input user/room
2026-05-31 23:34:57 +02:00

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"))
}
}