Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 636
Yonggoo Noh Avatar asked Nov 14 '15 02:11

Yonggoo Noh


3 Answers

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 %>
like image 68
Jeff K Avatar answered Nov 11 '22 04:11

Jeff K


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!

like image 6
Ryan K Avatar answered Nov 11 '22 03:11

Ryan K


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 %>
like image 3
Richard Peck Avatar answered Nov 11 '22 04:11

Richard Peck