0

I have a form on a page that is a single input field. I would like the user to be able to hit enter to submit the form. Unfortunately, the form gets submitted multiple times when enter is used to submit. I know the form is being submitted multiple times because there are multiple POST requests sent to the server. It happens in both development and production and it only happens sporadically.

= form_for thing, remote: true do |f|
  = f.text_field :name, placeholder: "hit enter to submit"

If I add a f.submit to the form, it will only submit once.

This is Rails 5 with turbolinks and jquery_ujs included in the application.js if that makes any difference.

UPDATE

I haven't been able to reproduce after making some changes.

I suspect the issue had to do with jquery_ujs being loaded multiple times on the page. This was due to turbolinks. More precisely, due to the fact that I was including all of my javascript in the body tag. turbolinks suggests adding your javascript files in the head tag. Since doing so, I have not been able to reproduce the error.

4

2 回答 2

1

使用 turbolink 时,使用正确的方法添加事件处理程序很重要。不要在您的 HTML 正文标记中放置任何 Javascript。使用 turbolinks 文档来确定您需要挂钩哪些事件以添加您自己的事件处理程序或对页面元素进行其他转换。

当前版本的 turbolinks:https ://github.com/turbolinks/turbolinks#full-list-of-events 旧版本的 turbolinks:https ://github.com/turbolinks/turbolinks-classic#events

当前版本也有一些关于使您的文档更改 idempotent 的建议,我也会这样做以添加事件侦听器。

于 2017-02-04T18:01:45.410 回答
0

另一个出现这种症状的案例是同时使用rails-ujsjquery_ujs。对于我的观察,如果在 application.jsrails-ujs之前jquery_ujs一切正常,但在另一种情况下出现了两次提交 ajax-forms。

于 2018-01-23T18:15:23.213 回答