Rails button_to remote gets messed up with onclick
I have a Rails 3 app that is trying to perform some controller action with a button and :remote => true. At the moment, I don't want to even worry about the success of the action, I just want to have it happen on its own, and have some onclick script that hides the element immediately.
I can't seem to get them both to work at the same time. Here's the code that I'm using, which does the action just fine:
<%= button_to "Ignore", url_for(:controller => "requests", :action => "ignore", :id => request.id), :remote=>true %>
Now, when I try to add the onclick, that part gets executed, but suddenly the request is treated as HTML, so I get sent to a new page instead of treating it as "remote":
<%= button_to "Ignore", url_for(:controller => "requests", :action => "ignore", :id => request.id), :remote=>true, :onclick => "ignore('request_'"i.t开发者_StackOverflowo_s"')" %>
As far as I can tell, the code for the button is created just fine, and the onclick works correctly, but adding that is making the request get messed up. Can anyone please help me out? Thanks a lot
Your onclick attribute has an error.
<%= button_to "Ignore", url_for(:controller => "requests", :action => "ignore", :id => request.id), :remote=>true, :onclick => "ignore('request_#{ i.to_s }'); return(false);" %>
However, you should consider doing this unobtrusively.
<%= button_to "Ignore", url_for(:controller => "requests", :action => "ignore", :id => request.id), :remote=>true, :'data-ignore-id' => i %>
then in the application.js
$('[data-ignore-id]').live('click', function(ev) {
ev.preventDefault();
var ignoreId = "request_" + $(this).attr('data-ignore-id').toString();
ignore(ignoreId);
});
Update
The problem is that the button_to helper is building a form when you supply a url_for. To the action that you are wanting to prevent is the onsubmit not the onclick.
<%= button_to "Ignore", url_for(:controller => "requests", :action => "ignore", :id => request.id), :remote=>true, :'data-ignore-id' => i %>
then in the application.js
$('[data-ignore-id]').submit(function(ev) {
ev.preventDefault();
var ignoreId = "request_" + $(this).attr('data-ignore-id').toString();
ignore(ignoreId);
});
Update #2 - change because of where the data-ignore-id attr is.
<form method="post" action="/requests/41/ignore" data-remote="true" class="button_to">
<div>
<input data-ignore-id="0" type="submit" value="Ignore" />
<input name="authenticity_token" type="hidden" value="7S3K+ZFhSZij1ZAmSeggG0SpPozNwHBk4zxjegLIiKs=" />
</div>
</form>
Change event to.
$('form > div input[data-ignore-id]').submit(function(ev) {
ev.preventDefault();
var ignoreId = "request_" + $(this).find('input[data-ignore-id]').attr('data-ignore-id').toString();
ignore(ignoreId);
});
this maybe helpful
=link_to "value", "javascript:function()", class: 'btn btn-default'
精彩评论