How to auto-submit Rails formhelper, when onchange occurs on select dropdown (populated from DB)

pete picture pete · Jul 15, 2013 · Viewed 7.9k times · Source

I have a form in my View with two dropdowns, both populated from db tables, where I'd like to auto-submit the form when onchange event occurs on either dropdown:

<%= form_for @products, url: products_path, method: :get do |f| %>
  <!-- POPULATE DROPDOWNS FROM DB DATA -->
  <%= select('post', 'state', @suppliers.collect {|s| [s.supp_state, s.id]}) %>
  <%= select('post', 'category_id', @categories.collect {|c| [c.cat_name, c.id]}) %>
  <div class='actions inline'><%= f.submit 'GO!' %></div>
<% end %>

I tried variants of the following but I'm quite new at Ruby/Rails/JS.. no luck so far:

<%= select('post', 'state', @suppliers.collect {|s| [s.supp_state, s.id]}, :onchange => "this.form.submit()") %>

<%= select('post', 'state', @suppliers.collect {|s| [s.supp_state, s.id]}, :input_html => {:onchange => "this.form.submit()") %>

Any advice is greatly appreciated!

Answer

david89 picture david89 · Jul 15, 2013

See documentation: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

The arguments goes like this:

select(object, method, choices, options = {}, html_options = {})

:onchange belongs to html options thus you need to fix your select box to this:

select('post', 'state', @suppliers.collect {|s| [s.supp_state, s.id]}, :onchange => "this.form.submit()")