简体   繁体   中英

Rails: Submit button outside form_tag

I'm using a button to perform processing in a group of selected check-boxes. The solution is based on RailsCast #165.

It's all working fine, but only if the submit_tag button is contained within the form (which is a table in my application). I'd like to place the submit button in the page header, but this breaks the connection to the form.

How can I place a submit button outside the body of the form?

<%= form_tag select_cosmics_path, method: :put do %>
  <%= submit_tag "Accept Checked", :class => "btn btn-primary" %> 

  <table class="table table-striped"> 
   .
   .
  <% @cosmics.each do |cosmic| %>
    <tr>
      <td><%= check_box_tag "cosmic_ids[]", cosmic.id %></td>
       .
       .
    </tr>
  <% end %>
  </table>
<% end %>

routes.rb

resources :cosmics do
  collection do
    put :select
  end
end

While this question is old, I think it might be worth pointing out a better option that doesn't rely on JavaScript.

HTML5 introduced form as an attribute that can be applied to any form control and will bind it to a specific form based on its id - even if the control isn't nested inside the form tag.

Example:

<form id="my_sample_form">
...
</form>

<input type="submit" value="Submit" form="my_sample_form">

This submit button will submit the form with the id specified in its form attribute.

Furthermore this isn't limited to submit buttons, but instead works for any form control and allows you to submit form partials that are positioned all over the place.

In contrast to most JavaScript solutions, you will keep all native form features like submitting on enter/return.

You can create a button outside the form, and use javascript to submit the form when the button is clicked:

HTML:

<button id="myBtn" class="btn btn-primary">Accept Checked</button>
...
<%= form_tag select_cosmics_path, method: :put, id: 'myForm' do %>
  ...
<% end %>

Javascript (using jQuery):

$(document).ready(function() {
  $('#myBtn').on('click', function() { $('#myForm').submit(); });
});

You can also add the javascript directly in the onClick attribute of the button.

With this coffescript code you can put the submit outside form just adding a 'outside-submit' class to the link.

HTML:

<a class="outside-form" data-formid="my-form">link to submit</a>

<form id="my-form">
  ...
</form>

CofeeScript:

jQuery ->
  $buttons = $(".outside-submit")

  for button in $buttons
    $button = $(button)
    $form = $("##{$button.data().formid}")
    $button.on 'click', -> $form.submit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM