简体   繁体   English

在 Phoenix LiveView 中提交后重置表单输入字段

[英]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:我认为至少有两种解决方案:

  • 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)在加msg价值,你的状态,使用value: @msg模板,并在复位handle_event (也许我会尝试先)
  • use a Javascript hook as suggested in the thread按照线程中的建议使用 Javascript 钩子

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.

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