Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: submit (via AJAX) when drop-down option clicked

What is the easiest and most graceful way to auto-submit an AJAX form when a drop-down box's option is selected? I'm creating an administration page where the admin can modify user permissions (where "permissions" is stored as an integer), and I would like the "permissions" field to be a drop-down box that automatically submits and updates when the administrator clicks on the option he wants the user to have.

Here's the stripped-down version of what I'm currently looking at. I need to know the best way to convert this to a remote form that automatically submits when an option is clicked on.

Feel free to point out any tangential suggestions or anything else...I'm relatively new to Rails, and only just reaching the point where I can write code without constantly referencing others' work.

<!-- This is the "index" view, by the way. -->
<% for membership in @story.memberships %>
  <% form_for membership do |f| %>
    <%= f.select :permissions, [['none', 0], ['admin', 9]] %>
  <% end %>
<% end %>
like image 239
Adam Rezich Avatar asked Feb 25 '09 16:02

Adam Rezich


3 Answers

There are a couple ways to handle this. Certainly the observe field approach is one, but you could also use a simple javascript or a remote_function to do it:

Here is the simple JS approach:

<% remote_form_for membership do |f| %>
    <%= f.select :permissions, [['none', 0], ['admin', 9]], {}, :onchange => 'this.form.submit()' %>
<% end %>

The other way would be something like this, and would eschew the form builder (and this may have a couple syntax errors):

<%= select_tag(:permissions, [['none', 0], ['admin', 9]], {:onchange => "#{remote_function(:url  => permissions_path(:story_id => story,
             :with => "'permission='+value")}"})

Personally I prefer the former.

like image 167
Scott Miller Avatar answered Oct 29 '22 19:10

Scott Miller


Three steps!

  1. Make your form_for a remote_form_for; add an id!
  2. Add an observe_field after your select
  3. Configure your observe_field to submit your form

The last bit looks something like:

<%= observe_field "id_of_select", :function => "$('form_id').submit();" %>
like image 22
Ian Terrell Avatar answered Oct 29 '22 19:10

Ian Terrell


In Rails 3:

<%= form_for(membership, :remote => true) do |f| %>`
  <%= f.select :permissions, [['none', 0], ['admin', 9]], {}, :onchange => 'this.form.submit();' %>
<% end %>

Note that it's this.form.submit(); not onsubmit. And don't forget the Javascript semicolon.

like image 27
Ron Avatar answered Oct 29 '22 18:10

Ron