2

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
blackgreen
  • 34,072
  • 23
  • 111
  • 129

3 Answers3

3

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.

2

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!

Julien C
  • 220
  • 2
  • 6
  • I tried having value: msg in the form, and then resetting it in handle event. It works the first time when msg is set, but since msg is never modified, the following times it does not work as assigns are not changed (msg is already "" and is set to ""). I fixed it with a hook and push_event –  Aug 30 '20 at 08:50
  • Right, makes sense. I just remembered that I had a little "gotcha" like that some time ago with textarea. Hopefully it'll be improved in future versions. – Julien C Aug 30 '20 at 08:59
0

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.

Hendri Tobing
  • 351
  • 5
  • 14
  • 1
    I cannot remove target @myself. I need this to have the LiveComponent handle the event rather than the parent LiveView –  Aug 30 '20 at 08:48