const autocomplete_query_delay_ms = 60; class AutocompleteText { constructor(text_id, dropdown_id, query_function) { this.text_id = text_id; this.dropdown_id = dropdown_id; this.query_callback = query_function.bind(this); document.getElementById(text_id).addEventListener("keyup", this.ac_delay(function(event) { this.query_callback(document.getElementById(this.text_id).value, this); }, autocomplete_query_delay_ms).bind(this)); } show_results(results) { var ul = document.getElementById(this.dropdown_id); ul.innerHTML = ''; for (var i = 0; i < results.length; i++) { var node = document.createElement('li'); node.setAttribute('class', 'dropdown-item'); node.appendChild(document.createTextNode(results[i])); ul.appendChild(node); node.addEventListener('click', (e) => { var element = e.target; var text_box = document.getElementById(this.text_id); text_box.value = element.innerHTML; var dropdown = bootstrap.Dropdown.getOrCreateInstance(text_box); dropdown.hide(); } ); } if (results.length == 0) { var node = document.createElement('li'); node.setAttribute('class', 'dropdown-item text-danger'); node.appendChild(document.createTextNode('No results')); ul.appendChild(node); } var dropdown = bootstrap.Dropdown.getOrCreateInstance(document.getElementById(this.text_id)); dropdown.show(); } ac_delay(callback, ms) { var timer = 0; return function() { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function() { callback.apply(context, args); }, ms || 0); }; } }