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
Related videos on Youtube
Author by
Nave
Updated on October 27, 2021Comments
-
Nave over 2 years
How do I add an onchange event here?
Framework: rails
Database: MySQLI 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 about 15 yearsI'm not quite sure what you mean?
-
Nave about 15 yearsi 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 about 15 yearsDOM 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 about 15 yearsI 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 almost 9 yearsthis works only with the prototype helpers, that are excluded from Rails 3.0.9 apidock.com/rails/ActionView/Helpers/PrototypeHelper/…
-
Aravin almost 7 yearsnot working!!! here's my code
<% tax = options_from_collection_for_select(@taxes, 'rate', 'name'), :onchange => 'calcInvoiceTotal()' %>
-
Karl Wilbur about 6 yearsCan you give a little more detail? Maybe explain why that would help.