Hi,
I have a Live Component with an autocomplete search input. I’m using phx-change
on the text input as an attribut to send an event to look up entries in the database matching the user input. I’m also using phx-change
on the form level to real-time validating all the form inputs and that works well. However, the autocomplete input is not getting validated as it is overriding the behaviour of the phx-change to send a search event instead of validating process. The problem is that I set the autocomplete as a required field and if the user omit it or delete it’s input, it should then get an error feedback as with other required fields.
Here is my autocomplete LC and I’m using AlpineJs to open or close the list of matching entries :
def render(assigns) do
~H"""
<div x-on:keyup.up="focusPrev" x-on:keyup.down="focusNext">
<div>
<label class="field_input_label required"><%= @label %></label>
<%= text_input @form, @field, id: "search-input" , class: "field_input_text ", autocomplete: "off" ,
phx_change: JS.push("search") , 'x-on:input.debounce.500ms': "open", 'x-on:keyup': "validate" %>
<%= error_tag @form, @field %>
</div>
<ul x-show="isOpen" x-ref="suggestions @keyup.enter="select">
<%= for {item, index} <- Enum.with_index(@items) do %>
<li id={"item-#{index}"} x-ref={"item-#{index}"} @click="select()">
<%= item %>
</li>
<% end %>
</ul>
</div>
"""
end
Is there any way to force the input to be validated after the user has changed it ?
I tried this :
phx_change: JS.push("search") |> phx_change: JS.push("validate")
It works partially. The events are fired sequentially as expected but it validates only this input and ignores other changes from other inputs and they get reset !
I also tried to fire a validate event from Javascript but it doesn’t work and no error shows up :
#on LC
'x-on:keyup': "validate"
#on javascript
validate() {
search = document.getElementById("search-input");
search.dispatchEvent(
new Event("input", { bubbles: true })
)
},
Or maybe the only other solution might be to use phx-keyup
instead of phx-change
?
Thanks for your help.