Tuesday, May 08, 2007

observe_field and radio_button

I had a group of radio buttons that I wanted to trigger some action when one of the button is selected. I setup an observe_field for each radio button but it didn't work. You can't specify observe_field to monitor a group of radio buttons. It would only monitor the first button. Actually, let me clarify that statement. It would work the first time a user click on the button but then subsequence click would not register as something has changed. Apparently, it keeps the last value and when the radio button is selected again, the last value and the current value is the same. That result in a no change. I ended up using onclick with remote_function to trigger the change event.

This is what I had and it doesn't work.
<%= radio_button_tag 'ship_method', 'pickup', :checked => true -%> Pickup

<%= radio_button_tag 'ship_method', 'deliver' -%> Deliver

<%= observe_field 'ship_method_pickup',
:url => { :controller => 'checkout', :action => 'ship_method_select' },
:on => 'click', :with => 'method' -%>

<%= observe_field 'ship_method_deliver',
:url => { :controller => 'checkout', :action => 'ship_method_select' },
:on => 'click', :with => 'method' -%>
This is what I ended up with
<input type="radio" name='ship_method' id='ship_method_pickup'
checked="checked" value="pickup"
onclick="<%=
remote_function(
:url => {:controller => 'checkout', :action => 'ship_method_select', :method => 'pickup'}
)-%>" />

7 comments:

Unknown said...

I had this problem too! I've noticed that there are a few of these mysterious problems in rails... have you submitted it as a bug?

Conrad said...

I didn't post a bug report for this issue.

Anonymous said...

Conrad,

instead of using observe_field you can use this:

<%= radio_button_tag "search_type", "date_range", true, :onclick => showDateRangeOptions %>

And then define showDateRangeOptions like this:

<% showDateRangeOptions = ""
showDateRangeOptions += "$(\'dateRangeOptions\').style.display = \'block\';\n" %>

Conrad said...

Thanks for the tip Rocky. I will give that a try.

Anonymous said...

Thank you very much for your post.
After spending hours trying to get the observe_field to work I came across you post that saved my day.

Thanks again.

Xavi said...

Thank you very much for your post. I spent time with this.

Anonymous said...

You actually don't need to reference another variable, you can do it inline (the important part is to escape the single quotes):

<%= radio_button_tag "search_type", "date_range", true, :onclick => "$(\'dateRangeOptions\').style.display = \'block\';" %>