Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 222
user502052 Avatar asked Mar 05 '12 17:03

user502052


People also ask

How do I make my submit button disabled?

1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.

How do you disable submit button until form is filled?

Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.


1 Answers

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

like image 57
Andrew France Avatar answered Sep 21 '22 09:09

Andrew France