Add a Rails 4 form with a link instead of a button

I see similar problems, but they seem far-fetched and mainly for previous versions of Rails.

What is the easiest way to submit a form with an anchor tag (link) instead of a regular button

<%= f.submit 'Search', :class => "button expand"%> 

What is the best way (best way) to change this to a link that sends?

+7
ruby ruby-on-rails
source share
3 answers

I often use js / jquery to submit forms. This is very useful if the submit button is outside the form or if there is more than one button that submits the same form.

 $(".submit-btn").click(function(event) { event.preventDefault(); $("#form-id").submit(); }); 

event.preventDefault(); prevents the default / submit button behavior.

Here is the coffeescript example that I used in the rails 4 project:

 ready = -> if $("#form-id").length > 0 $(".submit-btn").click (event) -> event.preventDefault() $("#form-id").submit() $(document).ready ready $(document).on "page:load", ready 

Also note: in this way, the link can be any type of element - optionally a submit button. You do not need to have a submit button inside the form, but if you run preventDefault , this will prevent the default form preventDefault behavior.

+9
source share

Submit

To extend the answers provided, HTML forms must be submitted using the submit button.

I’m not sure what special characteristics the submit button has on the link - it basically calls the submit action, which the link cannot have ( Information ):

enter image description here

-

Link

This means that if you want to replace the submit button with a link, you essentially have to map the submit method in your application. This can be done using JS (jQuery):

 #app/assets/javascripts/application.js $(document).on("click", "#your_link", function(){ $("#form").submit(); }); #app/views/controller/your_view.html.erb <%= form_tag your_path, id: "form" do %> <%= link_to "Submit", your_path, id: "your_link" %> <% end %> 
+4
source share

It is so simple:

Then:

 <%= f.submit '', :class => "hidden", :id => 'form_submit_button' %> content_tag(:a, 'Submit', :name => 'submit', :id => 'submit_link') 

and in JS:

 $(document).ready(function() { $(document).on("click","#submit_link",function() { $('#form_submit_button').click(); }); }); 

I am not sure about the exact sytax, so some syntax error may occur. Feel free to contact for further assistance.

0
source share

All Articles