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

后端 未结 5 2063
礼貌的吻别
礼貌的吻别 2021-02-04 10:14

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

相关标签:
5条回答
  • 2021-02-04 11:00

    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.

    0 讨论(0)
  • 2021-02-04 11:04

    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.

    0 讨论(0)
  • 2021-02-04 11:05

    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();" %>
    
    0 讨论(0)
  • 2021-02-04 11:05

    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.

    0 讨论(0)
  • 2021-02-04 11:09

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

    0 讨论(0)
提交回复
热议问题