What should I do? I ...">

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 do not want to connect another page (action = "/ URL").

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

+5
source share
3 answers

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

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

or

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

That would be a lot easier with form_tag than form_for . Try the following:

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

Also, do not forget that in foo() it must return false so that the form does not actually submit!

+3
source

Better put the function foo(); to the unobtrusive 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 %> 
+3
source

Source: https://habr.com/ru/post/1235938/


All Articles