DrCr/drcr/static/js/combobox.js
RunasSudo 3083117730
Implement custom combobox for account selection
Only on balance assertion edit page currently
2024-04-06 01:32:34 +11:00

65 lines
2.2 KiB
JavaScript

/* DrCr: Web-based double-entry bookkeeping framework
Copyright (C) 2022–2024 Lee Yingtong Li (RunasSudo)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
function updateComboboxInputs(elCombobox, elInput) {
elCombobox.querySelector('ul').querySelectorAll('li').forEach((elLi) => {
const liText = elLi.querySelector('.combobox-text').innerText;
if (liText.toLowerCase().startsWith(elInput.value.toLowerCase())) {
elLi.classList.remove('hidden');
elLi.classList.add('block');
if (liText == elInput.value) {
elLi.dataset.selected = 'selected';
} else {
elLi.dataset.selected = '';
}
} else {
elLi.classList.remove('block');
elLi.classList.add('hidden');
elLi.dataset.selected = '';
}
});
}
// Init combobox
document.querySelectorAll('.combobox').forEach((elCombobox) => {
const elInput = elCombobox.querySelector('input');
updateComboboxInputs(elCombobox, elInput);
// Update combobox options on input
elInput.addEventListener('input', (evt) => {
updateComboboxInputs(elCombobox, elInput);
});
// Open dropdown on click button
elCombobox.querySelector('button').addEventListener('click', (evt) => {
elInput.focus();
});
});
// Update combobox value on select
document.querySelectorAll('.combobox').forEach((elCombobox) => {
const elInput = elCombobox.querySelector('input');
elCombobox.querySelector('ul').querySelectorAll('li').forEach((elLi) => {
elLi.addEventListener('mousedown', (evt) => {
const liText = elLi.querySelector('.combobox-text').innerText;
elInput.value = liText;
updateComboboxInputs(elCombobox, elInput);
});
});
});