Search code examples
ruby-on-railslink-to

Submit form using link_to in rails


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?


Solution

  • 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()" %>