How to add an onchange event to select tag in rails

坚强是说给别人听的谎言 提交于 2019-11-26 20:14:13

问题


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



来源:https://stackoverflow.com/questions/979400/how-to-add-an-onchange-event-to-select-tag-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!