简体   繁体   中英

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.

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM