I have a search bar I created using HTMX and django forms that displays results correctly. I have a javascript selectOption() function filling the search bar with whatever the selected option is, but I am having trouble with the search results not going away after I select an option. Can this be handled through javascipt?
Additionally, the search bar returns random results once I type something and then delete it, leaving it blank. Is there something I could fill into hx-trigger to fix this issue?
See htmx tags below
widget_attrs_nha_autosearch = {
'class': 'form-control',
'data-user-entry': 1,
'disabled': value.get('read_only'),
'hx-post': reverse('django_p:n-autosearch'),
'hx-target': '#results',
'hx-trigger': "keyup changed delay:500ms, search"
}
See search-results html below
{% if results %}
<ul class="list-group col-xs-12">
{% for part in results %}
<li class="list-group-item d-flex justify-content-between align-items-center"
onclick="selectOption('{{ part.manufacturer_part_number }}')">{{ part.manufacturer_part_number }}</li>
{% endfor %}
</ul>
{% else %}
<p>No search results</p>
{% endif %}
<script defer>
function selectOption (partNumber) {
const input = document.querySelector('#id_override');
input.value = partNumber;
}
For your first issue, the problem is that when you select an option, you're not telling the results to go away. This is purely on the client side, so yes, this can be handled through Javascript.
function selectOption(partNumber) {
const input = document.querySelector('#id_override');
input.value = partNumber;
const results = document.querySelector('#results');
results.innerHTML = '';
}
For your second issue, the problem might be that when the search bar is emptied, a request is still sent to your Django backend with an empty query string, and the backend is returning some default results in this case.
One approach could be to modify your Django view to return no results if the query string is empty. Another approach would be to avoid sending the request in the first place if the search bar is empty. You can do this by adding a guard clause to your hx-trigger attribute like so
'hx-trigger': "keyup changed delay:500ms guard:$('id_override').value.trim() !== '', search"