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

StackOverflow https://stackoverflow.com/questions/17663099

  •  03-06-2022
  •  | 
  •  

Question

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!

Was it helpful?

Solution

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()")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top