[英]Reset form input field after submit in Phoenix LiveView
I have a form in Phoenix LiveView with a phx-submit binding.我在 Phoenix LiveView 中有一个带有 phx-submit 绑定的表单。 The form can be submitted by either clicking the "Send" button or by pressing the enter key in the text field.
可以通过单击“发送”按钮或在文本字段中按 Enter 键来提交表单。
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:和我的
handle_event
实现:
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 .我认为您的问题可能与此有关 - https://github.com/phoenixframework/phoenix_live_view/issues/624 。 Basically Liveview will not modify the focused input.
基本上 Liveview 不会修改焦点输入。
So when you press Enter, your focus is on the text input.因此,当您按 Enter 键时,您的焦点将放在文本输入上。
But when you click Submit, your focus changes to the button which lets Liveview reset the text input.但是当您单击提交时,您的焦点将更改为让 Liveview 重置文本输入的按钮。
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)msg
价值,你的状态,使用value: @msg
模板,并在复位handle_event
(也许我会尝试先)Hope it helps and hope I'm also correct!希望它有帮助,希望我也是对的!
can you remove phx_target: @myself
?你能删除
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.如果您有表单,那么
phx_submit
就足以完成此过程。
如果您使用value: @msg
方法,并将其与表单上的phi-change
事件结合使用,您@msg
将@msg
更新为@msg
的任何内容,然后将@msg
设置回 "" 的工作超出了第一个称呼。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.