views:

865

answers:

4

I have the following rails form (which works) but I want to remove the submit_tag and have the form submit as soon as a radio button selection is made. How do I do that?

<% form_tag({ :controller => "votes", :action => "create", :id => @item.id } ) do  %>
  <p>
    <% for i in 1..10 do %>
      <%=  radio_button_tag :rating, i %>&nbsp;<%=h i %>&nbsp;
    <% end %>
  </p>
  <p>
    <%= submit_tag "Create" %>
  </p>
<% end %>
A: 

Use Javascript

Use each radio button's onclick() event to call a function that calls submit() on the submit button.

I'm not really familiar with RJS in Rails, but this should be relatively easy.

Mark A. Nicolosi
+1  A: 

You'll want to add an onClick event to your radio button that calls this.formName.submit() where formName is your form ID. This will trigger the submit event when you click the radio button.

jess
A: 

An awesome way to achieve this unobtrusively is with lowpro and prototype. That way you can get all your event handlers out into your javascript so they don't pollute your view code. It is a very slick way of handling javascript events. Highly recommended.

railsninja
Rails actually use Prototype as it core JavaScript library (I think) for event registration, except that you don't have to mess about with JavaScript and simply use the Rails HTML helpers to make the JavaScript much easier to read and automatically generated.
Ash
Your right Rails does use prototype automatically. The problem is that these helpers pollute your code with pretty ugly javascript. I am suggesting using lowpro in conjunction with prototype to make your javascript unobtrusive and move javascript code into your .js files where it belongs. Your view code will be a lot cleaner as a result.
railsninja
+1  A: 

So I have found the precise solution (thanks for the input guys, it helped me redefine my Google searches). Everyone was on the right track, but none were spot on.

All that was needed was to add 'false, :onclick => "this.parentNode.submit();"' to the radio_button_tag form helper. The false is selected or not, and the rest is obvious.

The correct solution now looks like:

<% form_tag({ :controller => "votes", :action => "create", :id => @item.id } ) do  %>
    <% for i in 1..10 do %>
      <%=  radio_button_tag :rating, i, false, :onclick => "this.parentNode.submit();" %>&nbsp;<%=h i %>&nbsp;
    <% end %>
<% end %>
Ash