automatically select first finding in autocomplete fields on enter

This commit is contained in:
Stefan Strobel 2024-11-18 23:55:38 +01:00
parent 9afa7d709b
commit 7c1465428f
2 changed files with 16 additions and 3 deletions

View File

@ -27,6 +27,17 @@ function initialize_autocompletion_foreign_key_field(search_element) {
}); });
} }
// select first match if any on enter
search_element.addEventListener('keydown', (e) => {
if (e.key === "Enter") {
e.preventDefault();
first_search_result = search_element.parentElement.querySelector('li')
if (first_search_result) {
first_search_result.click()
}
}
});
new AutocompleteCustomUi( new AutocompleteCustomUi(
base_id, base_id+'-ac-ul', function(search_query, autocomplete_obj) { base_id, base_id+'-ac-ul', function(search_query, autocomplete_obj) {
api_ajax_request_without_send('GET', search_url+`?search=${encodeURIComponent(search_query)}`, function(method, url, json) { api_ajax_request_without_send('GET', search_url+`?search=${encodeURIComponent(search_query)}`, function(method, url, json) {
@ -47,7 +58,7 @@ function initialize_autocompletion_foreign_key_field(search_element) {
} }
} }
autocomplete_obj.show_results(nodes, function(data) { autocomplete_obj.show_results(nodes, function(data) {
var name = data['result'][name_field_name]; var name = data['result'][name_field_name];
if (image_field_name != '' && image_field_name != null) { if (image_field_name != '' && image_field_name != null) {
var image = data['result'][image_field_name]; var image = data['result'][image_field_name];
@ -72,7 +83,7 @@ function initialize_autocompletion_foreign_key_field(search_element) {
}); });
dflex_container.appendChild(span); dflex_container.appendChild(span);
}) })
}, function (){}); }, function (){});
} }
) )

View File

@ -38,7 +38,9 @@ class AutocompleteCustomUi {
this.query_callback = query_function.bind(this); this.query_callback = query_function.bind(this);
document.getElementById(text_id).addEventListener("keyup", this.ac_delay(function(event) { document.getElementById(text_id).addEventListener("keyup", this.ac_delay(function(event) {
this.query_callback(document.getElementById(this.text_id).value, this); if (event.key != 'Enter') {
this.query_callback(document.getElementById(this.text_id).value, this);
}
}, autocomplete_query_delay_ms).bind(this)); }, autocomplete_query_delay_ms).bind(this));
this.dropdown_data = {}; this.dropdown_data = {};