Submit Rails 4 form with link instead of button

后端 未结 3 1679
感动是毒
感动是毒 2021-02-04 17:12

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

3条回答
  •  醉梦人生
    2021-02-04 17:41

    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.

提交回复
热议问题