Nave
Nave

Reputation: 715

How to add an onchange event to select tag in rails

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

Upvotes: 21

Views: 55043

Answers (4)

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94284

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

Upvotes: 30

jmjm
jmjm

Reputation: 159

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

Upvotes: 0

AmitF
AmitF

Reputation: 1457

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

Upvotes: 7

marsjo
marsjo

Reputation: 81

try something like:

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

Upvotes: 8

Related Questions