Rails 4: Disable submit button after click

限于喜欢 提交于 2019-11-30 07:27:40

问题


I have a form_tag(foo_path(@foo), remote: true, id: 'foo-form' form and a submit button submit_tag ("Submit", :id => "foo-submit")

I'd like to disable the submit button after it has been clicked. Obviously, I cannot use something like onlick="jQuery(this).prop('disabled', true);" because it would break the remote functionality. I'm aware of the :disable_with data attribute for the submit_tag but it doesn't seem to work for me. It does generate the right form code but it has no effect. I'm not sure why it doesn't work but it might be due to the fact that I use prototype (legacy reasons) and jquery at the same time. Though, I only load ujs for jquery and not for prototype. However, all other query_ujs features work very well.

Is there another way to disable the submit button?


回答1:


use

submit_tag "Submit", id: "foo-submit", data: { disable_with: "Please wait..." }



回答2:


An alternative to the submit_tag is the button_tag. The button_tag allows you to add a font awesome spinner.

<%= button_tag 'Submit', class: 'btn btn-primary', 
      data: { disable_with: "<i class='fa fa-refresh fa-spin'>
      </i> Submitting Changes..."} %>



回答3:


You use CoffeeScript to do something like these lines:

jQuery ->
  $('.theform').submit ->
    $('input:submit').attr("disabled", true)

This disables the form submit button when the form with class="theform" is submitted. Depending on your need you adjust this to fit with your class/id for the form.




回答4:


The problem was caused by invalid HTML code. See <div> breaks <form> disable_with works now




回答5:


Since it is an ajax call, the resultant js.erb file from the corresponding action will be triggered.

The disable-on-click algorithm can be placed inside this js.erb file.

# in the controller
def foo_method
...
# will render js.erb for ajax call 
# assuming there is no .html view file in the directory
end

# in foo_method.js.erb
$('input:submit').attr("disabled", true);

It should bring you abck to the same page with the button noew disabled



来源:https://stackoverflow.com/questions/21812230/rails-4-disable-submit-button-after-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!