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 %>
In Rails 3:
Note that it's
this.form.submit();
not onsubmit. And don't forget the Javascript semicolon.I am using Rails 5 & I was also facing the similar situation but in my case the answer given by @scott was not submitting the form using
AJAX
as expected though I added theremote: true
option to the form (I don't havesubmit
button in the form).If somebody is also facing the similar problem try to change the JS code like this-
Hope this helps..
Three steps!
form_for
aremote_form_for
; add an id!observe_field
after yourselect
observe_field
to submit your formThe last bit looks something like:
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:
The other way would be something like this, and would eschew the form builder (and this may have a couple syntax errors):
Personally I prefer the former.
Learn how to do it without Rails using the framework of your choice. Using the Rails tags to perform AJAX can accomplish a task quickly, but can be very limiting when you need to change specific things about how the tag performs.
Read about web-standards and how to write unobtrusive javascript on these sites: http://ajaxian.com/ http://www.alistapart.com/
You'll be able to create more flexible, amazing UIs by learning how to perform AJAX without Rails.