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?

2 Answers 2

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. :)

Sign up to request clarification or add additional context in comments.

4 Comments

So, isn't there a jQuery bridge for the form.submit but only for the submit_tag?
The submit method of the FormBuilder calls submit_tag with the options passed on.
disable_with option was deprecated as of rails 3.2.5. Now use :data => {:disable_with => 'Submitting...'}. Source: apidock.com/rails/ActionView/Helpers/FormTagHelper/…
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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.