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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:49:36  来源:igfitidea点击:

rails - How to use onsubmit with form_tag

javascriptruby-on-railsruby

提问by Yonggoo Noh

I want to convert below code to form_foror form_tag.

我想将下面的代码转换为form_forform_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_tagor 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_tagthan form_for. Try this:

使用form_tag比这会容易得多form_for。试试这个:

<%= form_tag '#', onsubmit: "foo();" do %>

<% end %>

Also, don't forget that within foo(), it should return falseso 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 %>