Submit form using link_to in rails

random picture random · Jul 25, 2012 · Viewed 29.8k times · Source

I'm trying to submit a form using link_to as follows:

 <%= form_for(@post,  :url=> '/post/action', :method=> 'post', :html => {:id=>'form_id'} ) do |f| %>
  ....

 <%= link_to 'submit', "/post/action", :onclick=>"document.getElementById('form_id').submit()" %>

  ....

but it is not posting the form, it is simply redirecting my form to the specified url. Does anyone know how to do this?

Answer

Paulo Fidalgo picture Paulo Fidalgo · Feb 20, 2013

You can use:

<%= link_to 'submit', "#", :onclick => "$('#form_id').submit()" %>

if you are using JQuery and a later version of rails.

Above will work but if you have a really long page it will navigate to top of the page because of "#" so if you want to avoid that you can do:

<%= link_to 'submit', "", :onclick => "$('#form_id').submit()" %>