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))
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))
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 => 'your_onchange_handler()'
try something like:
:onchange => remote_function(:url => {:controller => 'controller', :action => 'action'})
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
You may want to add an onchange
attribute inline:
select_tag(:variable,options_from_collection_for_select(:all, :id, :name)), {:onchange => "(function(e){ e.target.value }).apply(this,arguments)"}
For my case, I'm not sure where to put the named functions, or sometimes I find it tedious to create a function just to create a simple tag. So people tend to write an inline function.
but a simple line like {onchange: "e.target.value"}
won't work, because there are no variables (e.g. event
) defined.
Solution would be a self executing function that accepts arguments