Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 888
port5432 Avatar asked Jun 22 '13 12:06

port5432


1 Answers

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.

like image 65
Michael Feihstel Avatar answered Sep 17 '22 17:09

Michael Feihstel