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.
When using turbolinks, it's important that you add event handlers using the correct method. Do not place any Javascript in your HTML body tag. Use the turbolinks documentation to determine which events you need to hook into to add your own event handlers or make other transformations of page elements.
Current version of turbolinks: https://github.com/turbolinks/turbolinks#full-list-of-events Older version of turbolinks: https://github.com/turbolinks/turbolinks-classic#events
The current version also has some recommendations on making your document changes idempotent, which I would do for adding event listeners as well.