random
random

Reputation: 10309

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?

Upvotes: 13

Views: 34850

Answers (2)

Paulo Fidalgo
Paulo Fidalgo

Reputation: 22296

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

Upvotes: 25

Stefan Kanev
Stefan Kanev

Reputation: 3040

I think both things happen. The browser starts to submit the form, but it also follows the link's href. You can fix it by linking to # instead of /post/action...

...however, I don't recommend doing it. There are a few better approaches:

First, you can use a button instead of a link. You'll have to style it to make it look like a link, but that should not be a problem. It will be better, because it won't break the Principle of Least Surprise (people who read the code expect forms to be submitted with buttons) and you won't need the JavaScript.

If you insist on using a link, you should at least move the JavaScript code from the view to a JavaScript file. Then have this behavior added unobtrusively (although, you won't have a good fallback with the link). Assuming you're using jQuery, it should be as simple as:

$(document).on('click', '[data-submit-form]', function(e) {
  e.preventDefault();
  $(this).closest('form').submit()
}

Upvotes: 8

Related Questions