HTMX search suggestions and search from signle input

213 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

Another approach would be to make the appropriate requests on the target divs themselves by simply listening to your desired events from the search input field.

<input type="text" id="search-input"/>

<div 
   hx-get="suggestion_endpoint" 
   hx-trigger="keyup from:#search-input" 
   id="suggestion-div">
</div>

<div 
   hx-get="search_endpoint" 
   hx-trigger="keyup[keyCode==13] from:#search-input"
   hx-on::after-request="document.getElementById('suggestion-div').innerHTML = '';">
</div>