Reputation: 1943
I want to convert below code to form_for
or form_tag
.
<form onsubmit="foo()">
What should I do? I don't want to connect another page(action="/URL").
I just want function foo()
to fire when this form is submitted.
Upvotes: 18
Views: 17235
Reputation: 76774
You'll be better putting the foo();
function into the unobtrusive asset pipeline in Rails:
#app/assets/javascripts/application.js
var foo = function(e) {
e.preventDefault();
...
};
$(document).on("submit", "#form", foo(e));
You can accompany this with ...
<%= form_tag "#", id: "form" do %>
Upvotes: 3
Reputation: 543
This should be easy to do with either form_tag
or form_for
. Example:
<%= form_for @model, :html => { :onsubmit => "foo()" } %>
<% end %>
or
<%= form_tag '#', :html => { :onsubmit => "foo()" } %>
<% end %>
Upvotes: 24
Reputation: 4053
This would be much easier with form_tag
than form_for
. Try this:
<%= form_tag '#', onsubmit: "foo();" do %>
<% end %>
Also, don't forget that within foo()
, it should return false
so that the form doesn't actually submit!
Upvotes: 6