简体   繁体   中英

Reset form input field after submit in Phoenix LiveView

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:

  • 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!

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.

如果您使用value: @msg方法,并将其与表单上的phi-change事件结合使用,您@msg@msg更新为@msg的任何内容,然后将@msg设置回 "" 的工作超出了第一个称呼。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM