n8o
n8o

Reputation: 1943

rails - How to use onsubmit with form_tag

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

Answers (3)

Richard Peck
Richard Peck

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

Jeff K
Jeff K

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

Ryan K
Ryan K

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

Related Questions