I would like to have single input box for user to type the query. While they type it HTMX should call one endpoint for suggestions, but when user hits the enter button it should call another endpoint. And depending on call two different divs should be updates. On suggestion only suggestion box, but on search (when enter is hit) suggestion div should be deleted and search area should get new data.
I found one answer Multiple targets for Htmx but this is actually not working. I'm not getting any query to the back and by using only "keyup delay:500ms" every keyboard stroke calls back (even arrow keys) which is not ideal.
One way of solving this is wrapping the input
in a form
targeting your alternate endpoint. The form will be triggered on ENTER by default, and the search suggestions endpoint on keyup as defined in the hx-trigger
atttribute:
<form hx-post="another-endpoint.php" hx-target="#searchArea">
<input id="searchQuery" name="searchQuery" hx-post="suggestions.php" hx-trigger="keyup delay:500ms" hx-target="#suggestionBox" />
</form>
<div id="suggestionBox"></div>
<div id="searchArea"></div>
If another-endpoint
returns
<input id="searchQuery" name="searchQuery" hx-post="suggestions.php" hx-trigger="keyup" hx-target="#suggestionBox" hx-swap-oob="true" />
<div id="suggestionBox" hx-swap-oob="true"></div>
{Result of the search}
the suggestionBox
div will be emptied and the result will appear on the searchArea
div. The <input id="searchQuery">
is included as an OOB swap to prevent the keyup of the ENTER updating the suggestionBox.
See hx-trigger and hx-swap-oob for more details