Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 664
Nave Avatar asked Jun 11 '09 05:06

Nave


People also ask

Can we use Onchange in select tag?

The other difference is that the onchange event also works on <select> elements.

What is Onchange tag in HTML?

Definition and Usage The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

Why is Onchange not working?

onchange is not fired when the value of an input is changed. It is only changed when the input's value is changed and then the input is blurred. What you'll need to do is capture the keypress event when fired in the given input. Then you'll test the value of the input against the value before it was keypressed.

What does Onchange return?

An onChange event handler returns a Synthetic Event object which contains useful meta data such as the target input's id, name, and current value. We can access the target input's value inside of the handleChange by accessing e. target.


2 Answers

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()'
like image 149
Daniel Vandersluis Avatar answered Oct 12 '22 21:10

Daniel Vandersluis


try something like:

:onchange => remote_function(:url => {:controller => 'controller', :action => 'action'})
like image 33
marsjo Avatar answered Oct 12 '22 19:10

marsjo