5

I'm trying to prevent a form from being "double posted", when the user either clicks twice or hits submit twice.

I've seen a couple posts on this, but they haven't hit this issue per se. I can't seem to get the below to stop double-posts, and I'm getting the feeling it's related to the remote => true (using ajax to show the content on the page).

Below is my form:

    <%= form_for([@posts, @comment], :remote => true) do |f| %>

      <%= f.text_field :comment %>

      <%= f.submit "Submit", class: "btn btn-large btn-primary", :style => 'display: none;', :disable_with => '' %>

    <% end %>

Any recommendations would be great. Thank you!

user749798
  • 5,210
  • 10
  • 51
  • 85
  • 1
    http://stackoverflow.com/questions/11505801/prevent-double-submits-in-a-rails-ajax-form – denis.peplin Jul 30 '12 at 04:18
  • it works fine for "clicking" but doesn't work for when someone hits enter...which is what people do when you hide the submit button. That's why this question is different from the one on the link – user749798 Jul 31 '12 at 00:11

2 Answers2

10

Use the disable_with option

<%= submit_tag :submit, :id => 'submit_button', :value => "Create!", disable_with: "Creating..." %>
YaBoyQuy
  • 783
  • 5
  • 8
  • It should be noted that this is currently broken on Safari (8.0.3, in my case). See: https://github.com/rails/jquery-ujs/issues/306 If anyone has a sane workaround, I'd love to hear it! – elsurudo Feb 16 '15 at 18:46
  • 1
    Please update the answer for newer Rails versions, see the answer below. – lafeber Feb 25 '20 at 10:58
10

The other answer didn't work for me — I believe it was from the Rails 2 era. According to the docs, the disable_with attribute should be added within a data attribute, like so:

<%= submit_tag "Complete sale", data: { disable_with: "Please wait..." } %>
ivanreese
  • 2,718
  • 3
  • 30
  • 36