混合单选按钮和 text_field单选、按钮、text_field

2023-09-06 21:59:59 作者:我的宝藏男孩

我正在尝试将单选按钮和 text_field 组合为一个值:

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).

我尝试给text_field取另一个名字,更新后替换了控制器中的:system值,但是看起来很脏……

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 ?

推荐答案

这里不能直接将radio_button 和text_field 混用为同一个字段.我认为您可以定义一个额外的 radio_button 字段,该字段将被隐藏,并且当用户输入 text_field 时其值将得到更新.

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

在上面,您将在 text_field 上编写 onchange 事件,每当在 text_field 中输入值时,它会将隐藏的 radio_button 的值设置为 text_field_value.

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 .. :)