How to add an onchange event to select tag in rail

2019-01-14 03:48发布

问题:

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))

回答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 => 'your_onchange_handler()'


回答2:

try something like:

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


回答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



回答4:

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