Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit Rails 4 form with link instead of button

I see some issues similar but they seem contrived and mostly for previous versions of Rails.

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

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

What is the most concise way (best practice) way to change that to a link that submits?

like image 323
Chris Valentine Avatar asked Jul 16 '14 02:07

Chris Valentine


1 Answers

I often use js/jquery to submit forms. It's very useful if the submit button is outside of 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();
});

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

Here is a coffeescript example I have used in a 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, this way the link can be any type of element - not necessarily a submit button. You do not have to have the submit button inside the form, but if you do the preventDefault will prevent the default form submission behaviour.

like image 113
Nicholas.V Avatar answered Sep 21 '22 18:09

Nicholas.V