I'm trying to combine radio buttons and text_field for a single value :
= f.radio_button :system, "bacteria"
Bacteria
= f.radio_button :system, "mammalian"
Mammalian
= f.radio_button :system, "yeast"
Yeast
= f.radio_button :system, "insect"
Insect
= f.radio_button :system, "other"
Other:
= f.text_field :system, class:"input-small"
When I submit, nothing happens because a blank value is given in params even if a radio is checked (I think it considers the text field).
I tried to give another name to the text_field, and replaced the :system value in the controller after updating, but it looks like a dirty way...
Do you have any cleaner ideas ?
Here you can not directly mix radio_button and text_field together for the same field. I think you can define one extra radio_button field that will be hidden and whose value will get updated when user enters into text_field.
= f.radio_button :system, "bacteria"
Bacteria
= f.radio_button :system, "mammalian"
Mammalian
= f.radio_button :system, "yeast"
Yeast
= f.radio_button :system, "insect"
Insect
= f.radio_button :system, "other"
Other:
= f.radio_button :system, nil, :id => :hidden_radio, :style => "display:none"
= f.text_field :free_system_input, class:"input-small", :id => :free_system_input
In above you will be writing onchange event on text_field and whenever value gets entered inside text_field it will set hidden radio_button's value to the text_field_value.
:javascript
$("free_system_input").keyup(function(){
$("hidden_radio").val($(this).val())
})
Above code is just to give idea how to deal with issue and will not work just as it is .. :)
Thanks to Sandip's help, I managed to fix my problem!
Here is the view:
= f.radio_button :system, "bacteria"
Bacteria
= f.radio_button :system, "mammalian"
Mammalian
= f.radio_button :system, "yeast"
Yeast
= f.radio_button :system, "insect"
Insect
%br/
= f.radio_button :system, nil, id: 'other_system_radio',
checked: radio_checked?('system', f.object.system)
Other:
%input.input-small#other_system_text{ value: text_input?('system', f.object.system) }
I use helper functions to manage edit form (fill the text field if the value if different from the given ones):
def radio_checked?(type,val)
case type
when 'system'
['bacteria', 'mammalian', 'yeast', 'insect'].include?(val) ? '' : 'checked'
end
end
def text_input?(type,val)
case type
when 'system'
['bacteria', 'mammalian', 'yeast', 'insect'].include?(val) ? '' : val
end
end
And a bit of Javascript to select the "Other" radio button when the user focuses on the text field:
@handle_other_field = ->
$('#other_system_text').focus( -> $('#other_system_radio').attr('checked','checked'))
$('#other_system_text').keyup( -> $('#other_system_radio').val($(this).val()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With