javascript rails - 如何将 onsubmit 与 form_tag 一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33704365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails - How to use onsubmit with form_tag
提问by Yonggoo Noh
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.
我只想function foo()
在提交此表单时触发。
回答by Jeff K
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 %>
回答by Ryan K
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()
,它应该return false
使表单实际上不会提交!
回答by Richard Peck
You'll be better putting the foo();
function into the unobtrusiveasset 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 %>