How to add an onchange event to select tag in rails

50,455

Solution 1

select_tag takes an options hash as its final parameter, in which you can add any HTML attributes for the select. So to add an onchange attribute:

select_tag :variable, options_from_collection_for_select(:all, :id, :name), onchange: 'yourOnChangeHandler()'

Solution 2

try something like:

:onchange => remote_function(:url => {:controller => 'controller', :action => 'action'})

Solution 3

For a select_tag, just add:

{:onchange => "myHandler();" }

Also, if onchange doesn't work you might want to try onChange with a capital C.

Finally, make sure NOT TO CONFUSE a select_tag with a form select.

See my answer to a similar question, only regarding a form select and not a select_tag

Adding An Onchange Event To A Form Select

Share:
50,455

Related videos on Youtube

Nave
Author by

Nave

Updated on October 27, 2021

Comments

  • Nave
    Nave over 2 years

    How do I add an onchange event here?

    Framework: rails
    Database: MySQL

    I am populating the options from the database and that made me use options_from_collection_for_select

    select_tag(:variable,options_from_collection_for_select(:all, :id, :name))
    
  • Bruce
    Bruce about 15 years
    I'm not quite sure what you mean?
  • Nave
    Nave about 15 years
    i have an action in my controller to be executed and not a javascript event hander. will i be able able to do it with onchange event or are there any other ways?
  • Bruce
    Bruce about 15 years
    DOM events can only fire javascript event handlers. You could have your event handler make an AJAX call to the action you want executed, though.
  • Bruce
    Bruce about 15 years
    I don't know exactly what you want to do of course, but take a look at the observe_field (api.rubyonrails.org/classes/ActionView/Helpers/…) method -- you can use that instead of the above onchange handler to set up a Rails action to be called when an input is changed. Hopefully that will put you in the right direction!
  • damoiser
    damoiser almost 9 years
    this works only with the prototype helpers, that are excluded from Rails 3.0.9 apidock.com/rails/ActionView/Helpers/PrototypeHelper/…
  • Aravin
    Aravin almost 7 years
    not working!!! here's my code <% tax = options_from_collection_for_select(@taxes, 'rate', 'name'), :onchange => 'calcInvoiceTotal()' %>
  • Karl Wilbur
    Karl Wilbur about 6 years
    Can you give a little more detail? Maybe explain why that would help.