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

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 %>

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.

Three steps!
Make your form_for a remote_form_for; add an id!
Add an observe_field after your select
Configure your observe_field to submit your form
The last bit looks something like:
<%= observe_field "id_of_select", :function => "$('form_id').submit();" %>

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.

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.

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 the remote: true option to the form (I don't have submit button in the form).
If somebody is also facing the similar problem try to change the JS code like this-
<% form_for membership remote: true, id: '#member_form' do |f| %>
<%= f.select :permissions, [['none', 0], ['admin', 9]], onchange: '$("#member_form").trigger("submit");' %>
<% end %>
Hope this helps..

Related

How can I create a button which adds fields to a Rails form

I have a form in Rails which uses fields_for to accept nested attributes:
<%= form_with(model: #combat_tracker, url: form_url) do |f| %>
…
<%= f.fields_for :zones do |zone| %>
<div class="zone-field">
<%= zone.text_field :name %>
<%= zone.check_box :_destroy %>
<%= zone.label :_destroy, "Remove zone" %>
</div>
<% end %>
…
<% end %>
Currently this gives me input fields for any existing zones on #combat_tracker. I want to add a button that will dynamically add a new zone-fields div for a new zone to be added when the form is submitted.
I’m using Rails 7 and assume the solution will involve the use of Turbo or possibly Stimulus, but can’t quite figure out the best way to do this. Thanks.
I don't think you need Turbo or Stimulus. Take a look at cocoon gem, it should do exactly what you're looking for.
Explaining all process here is quite complex for me, but try to follow this guide if the gem's one is too long.

How to display only unchecked items in active admin for has many relationship?

I am using Ruby on Rails 5 with active admin as a backend for resources management. I need to show the only unchecked items for a check_boxes field all the time in new and edit action. Instead of running a complex query for the collection I think this is the best way to manage. All of my associated models stuff related to this are working fine.
It should show only 2nd item if it is not checked already.
Right now my code snippet is
f.input :subscribers, :as => :check_boxes, :collection => Subscriber.all.collect {|subscriber| [subscriber.email, subscriber.id]}
Is there any way in active admin to display only unchecked values ?
Have you considered using collection_check_boxes for this case?
It would look something like this:
<%= f.collection_check_boxes(:subscribers_ids, Subscriber.all, :id, :email) do |b| %>
<% if !b.check_box.include?(checked="checked") %>
<%= b.label %>
<%= b.check_box %>
<% end %>
<% end %>
I think that should solve your problem. If you want to learn more about collection_check_boxes

Rails remote form submit through javascript

I'm trying to create a very small simple form that edits a single checkbox, and submits automatically with AJAX when the checkbox is modified. Here's the code, which other SO questions imply should work:
<%= form_for(workitem, :remote => true) do |f| %>
<%= f.check_box :is_complete, :onchange => 'this.form.submit()' %>
<% end %>
The problem is that this results in a full page HTML submit, rather than an AJAX submit. How do I trigger an AJAX submit?
This seems to work:
$(this.form).submit();
Good 'ol jquery to the rescue.
This is simply in Rails way :
$("#myform").trigger('submit.rails');
find it here : same question

Keep Rails from redirecting a page

I'm having some trouble and I hope someone can help me. I have an erb file with a form in it that has a button. When you click the button it redirects the page elsewhere and shows the erb file that I told it to point to. This is great except I'd really like to stuff the content of that directed-to erb file into a div that is sitting below my form. My view looks something like this.
<div id="formentry">
<%= form_for #time, :url => {:action => 'list'}, :remote => true, :update => 'results' do |f|%>
<%= select :time, :period, TimeSelectModel::TIMEVALUES %>
<%= f.submit "Submit" %>
<% end %>
</div>
<div id="results"></div>
From what I've read online this seems like the approach you're supposed to take to do this in Rails3 but I'm not finding that it's working. (see: the page is completely redirecting) What am I doing wrong? Thanks.
My impression from your post is that you want to submit a form and show the results without leaving the page. What you are looking to do requires use of javascript/ajax.
Checkout railscast 205 for an example of how to do this.

Easy way to turn a Rails form into an AJAX form?

I have the following form in my Rails application:
<% form_tag password_resets_path, :id => 'recoverPasswordForm' do %>
<label for="passwordRecoveryEmailAddress">Email Address:</label>
<%= text_field_tag "passwordRecoveryEmailAddress" %>
<%= submit_tag 'Recover' %>
<br />
<div id="forgotPasswordLoginLinkContainer">
<a id="forgotPasswordLoginLink" href="/login">Login Instead</a>
</div>
<% end %>
When this form is submitted, the page must reload. I would like to easily turn this form into an AJAX form, such that the form submits via AJAX, and a page reload does not happen.
I could do this easily using jQuery, hooking into the .submit() function. But, I am curious: does Rails provide some easy way to turn any given form into an AJAX form? Or, what's the simplest (yet elegant) way possible? Maybe something like
<% form_tag password_resets_path, :id => 'recoverPasswordForm', :ajax => true do %>
I'm using Rails 2.
Yes, and you were close with your guess. Rails 3 allows you to do form_tag ..., :remote => true to let the form use AJAX if Javascript is available.
See http://railsapi.com/doc/rails-v3.0.0/classes/ActionView/Helpers/FormTagHelper.html#M002483

Resources