I have a form in Phoenix LiveView with a phx-submit binding. The form can be submitted by either clicking the "Send" button or by pressing the enter key in the text field.
My problem is that if I submit the form by pressing the enter key, the input field IS NOT cleared, however if I submit by clicking the button the input field IS cleared.
I would like the input field to be cleared in both cases.
Below is my form:
<%= f = form_for :chat_form, "#", phx_submit: :send, phx_target: @myself %>
<%= text_input f, :msg, autocomplete: "off" %>
<%= submit "Send" %>
</form>
and my handle_event
implementation:
def handle_event("send", %{"chat_form" => %{"msg" => msg}}, socket) do
name = socket.assigns.name
Endpoint.broadcast("chat", "new_msg", %{sender: name, text: msg})
{:noreply, socket}
end
I think your issue might be related to this - https://github.com/phoenixframework/phoenix_live_view/issues/624. Basically Liveview will not modify the focused input.
So when you press Enter, your focus is on the text input.
But when you click Submit, your focus changes to the button which lets Liveview reset the text input.
I think there are at least 2 solutions:
msg
value to your state, use value: @msg
in the template, and reset it in the handle_event
(maybe what I would try out first)Hope it helps and hope I'm also correct!