Submit Rails 4 form with link instead of button

后端 未结 3 1687
感动是毒
感动是毒 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:32

    Submit

    To extend the answers provided already, HTML forms have to be submitted with a submit button.

    I'm not sure exactly what special characteristics the submit button has over a link - it essentially calls the submit action, which a link cannot (info):

    enter image description here

    --

    Link

    This means if you wish to replace a submit button with a link, you'll essentially have to mimick the submit method in your application. This can be done with 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 %>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 17:47

    This 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 exact sytax so there might be some syntax error. Feel free to ask for more help.

    0 讨论(0)
提交回复
热议问题