HTMX Active Search - min of 3 characters

286 views Asked by At

I'm following along with the HTMX Active Search example. I need to change it so it does not trigger the request unless 3 characters have been entered in the search input box.

<input class="form-control" type="search" 
   name="search" placeholder="Begin Typing To Search Users..." 
   hx-post="/search" 
   hx-trigger="keyup changed delay:500ms, search" // can I add something here to only trigger if 3 or more characters are entered
   hx-target="#search-results">

I know can deal with this on the server side i.e. abort the request if fewer than 3 characters are entered, but I'd rather avoid the round trip and server call. Having said that, I do not want a js solution either :)

2

There are 2 answers

1
mariodev On BEST ANSWER

As per docs:

The "this" symbol will be set to the current element.

So you should be able to do:

keyup[this.value.length > 3] changed...
1
punund On

You may try to include hx-validate attribute and use HTML5 validation API:

<input class="form-control" type="search"
   hx-validate
   min-length="3"
...>

as per documentation.