Reset form input field after submit in Phoenix LiveView

3.4k Views Asked by At

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
3

There are 3 best solutions below

2
On BEST ANSWER

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:

  • add the 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)
  • use a Javascript hook as suggested in the thread

Hope it helps and hope I'm also correct!

0
On

If you use the value: @msg approach mentioned above and couple it with a phi-change event on the form where you simple update the @msg to whatever has been typed, then the setting the @msg back to "" works beyond the first call.

1
On

can you remove phx_target: @myself? As it is usually used if you are using a link or button to send an event to itself. If you have a form, then phx_submit is sufficient to this process.