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.
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 %>
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!
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With