rails - 如何使用带有form_tag的onsubmit

时间:2022-11-24 10:19:08

I want to convert below code to form_for or form_tag.

我想将下面的代码转换为form_for或form_tag。

<form onsubmit="foo()">

What should I do? I don't want to connect another page(action="/URL").

我该怎么办?我不想连接另一个页面(action =“/ URL”)。

I just want function foo() to fire when this form is submitted.

我只想在提交此表单时触发函数foo()。

3 个解决方案

#1


9  

This should be easy to do with either form_tag or form_for. Example:

使用form_tag或form_for很容易做到这一点。例:

<%= form_for @model, :html => { :onsubmit => "foo()" } %>
<% end %>

or

要么

<%= form_tag '#', :html => { :onsubmit => "foo()" } %>
<% end %>

#2


4  

This would be much easier with form_tag than form_for. Try this:

使用form_tag比使用form_for更容易。尝试这个:

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

另外,不要忘记在foo()中,它应该返回false,以便表单实际上不提交!

#3


3  

You'll be better putting the foo(); function into the unobtrusive asset pipeline in Rails:

你最好把foo();在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 %>

#1


9  

This should be easy to do with either form_tag or form_for. Example:

使用form_tag或form_for很容易做到这一点。例:

<%= form_for @model, :html => { :onsubmit => "foo()" } %>
<% end %>

or

要么

<%= form_tag '#', :html => { :onsubmit => "foo()" } %>
<% end %>

#2


4  

This would be much easier with form_tag than form_for. Try this:

使用form_tag比使用form_for更容易。尝试这个:

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

另外,不要忘记在foo()中,它应该返回false,以便表单实际上不提交!

#3


3  

You'll be better putting the foo(); function into the unobtrusive asset pipeline in Rails:

你最好把foo();在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 %>