Observe Field and Radio Buttons in Rails
Posted by Vince Wadhwani on Feb 14, 2008
By this stage it should have been easy for me to get an observe field working in Rails but for some reason I just couldn't pull it off. I googled a bunch and still couldn't get an answer I was looking for (that worked). If you're in the same boat, here's a tiny snippet of code that will let you show and hide a div with radio buttons. Handy if you want to show different forms depending on the selection.
Purchase Order
<%= radio_button_tag ('method', 'po', checked = false,
options = {:onclick => "Element.show('p2'); Element.hide('p1');"}) %>
Credit Card
<%= radio_button_tag ('method', 'card', checked = false,
options = {:onclick => "Element.show('p1'); Element.hide('p2');"}) %>
The above code snippet assumes you've got two divs. One for p1 and the other for p2. They might look like this:
<div id = "p1" style="display:none"> form 1 goes here! </div> <div id = "p2" style="display:none"> form 2 goes here! </div>
I'm working on a legacy 1.2.6 rails application so the above is untested in Rails 2.0.2 but it *should* work. If for some reason it doesn't make sure you've got the requisite <%= javascript_include_tag :defaults %> somewhere to make the ajax hum.