helper to determine if radio/checkbox needs to be checked
It's designed to be used in a Rails helper. You can either pass it the object, method, and value (the same parameters as, for example, radio_button) or name and value (the same parameters as radio_button_tag).
1 def checked?( *args ) 2 if args.length == 3 3 object, method, value = args 4 if params[object] && params[object][method] && params[object][method] == value 5 'checked' 6 end 7 elsif args.length == 2 8 name, value = args 9 if params[name] && params[name] == value 10 true 11 end 12 end 13 end
Here's an example usage:
1 <%= radio_button 'person', 'age', '12', :checked => checked?( 'person', 'age', '12' ) %>
If params[:person][:age] exists and it equals '12', then 'checked?' returns 'checked'; otherwise, it returns nil.