How to disable a form submit button "a là Ruby on Rails Way"?
Asked Answered
P

2

26

I am using Ruby on Rails 3 and I would like to disable and toogle the CSS class of a form.submit when the form is AJAX submitted and until the AJAX HTTP request is completed (I am using the default jQuery framework for JavaScript).

My form is the following:

<%= form_for(@article, :remote => true) do |form| %>
    ...
    <%= form.submit(nil, {:id => 'button_id', :class => 'button_class'}) %>
<% end %>

How can I make that in a "common"/"good"/"proper" way?

Phaeton answered 5/3, 2012 at 17:13 Comment(0)
H
47

The Rails jQuery bridge (jquery_ujs.js) code actually has a helper for this.

<%= form.submit "Save", id: "button_id", class: "button", disable_with: "Submitting..."

It will replace the button text with the value you give.

See http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-submit_tag

API change: as Renan suggests in a comment below, as of Rails 4 beta there is a deprecation notice on the disable_with option. It should be changed to be a data attribute:

<%= form.submit "Save", id: "button_id", class: "button", data: {disable_with: "Submitting..."} %>

This should work with all recent versions of Rails as it's what the option did anyway. So it'll be one less deprecation notice to fix when you upgrade to Rails 4. :)

Hothead answered 5/3, 2012 at 19:44 Comment(4)
So, isn't there a jQuery bridge for the form.submit but only for the submit_tag?Phaeton
The submit method of the FormBuilder calls submit_tag with the options passed on.Hothead
disable_with option was deprecated as of rails 3.2.5. Now use :data => {:disable_with => 'Submitting...'}. Source: apidock.com/rails/ActionView/Helpers/FormTagHelper/…Passport
There's no deprecation notice in the latest 3.2.13 release of Rails but it is in the 4.0.0-beta1 so I've updated my answer to reflect that. Thanks.Hothead
H
1

Following Rails 7, library @rails/ujs is no longer on by default. So :disable_with is not integrated.

Since Rails 7, Turbo is installed by default and it should prevent a double submit.

I my case, I had this issue because I had

= form_with model:, url:, data: { turbo: false } do |form|`

Removing data: { turbo: false } solved the issue.

Homeward answered 4/7 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.