2012-08-03 34 views
5

我想單選按鈕和text_field合併爲一個單一的值:混合單選按鈕和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.text_field :system, class:"input-small" 

當我提交,什麼都不會發生,因爲空值在PARAMS給出即使在無線檢查(我認爲它認爲文本字段)。

我試着給另一名到text_field,並替換:更新後的控制器系統的價值,但它看起來像一個骯髒的方式...

你有任何清潔劑的想法?

回答

2

在這裏你不能直接混合radio_button和text_field在同一個領域。 我想你可以定義一個額外的radio_button字段,這個字段將被隱藏,並且當用戶輸入到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。

:javascript 
$("free_system_input").keyup(function(){ 
    $("hidden_radio").val($(this).val()) 
}) 

上面的代碼只是爲了給知道如何處理的問題,因爲它不會只是工作.. :)

2

感謝的Sandip的幫助下,我成功地解決我的問題!

這裏是視圖:

= 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) } 

我用的輔助功能來管理編輯表格(填寫文本字段,如果值,如果從給定的情況不同):

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 

,有點的Javascript來選擇「其他」單選按鈕,當用戶專注於文本字段時:

@handle_other_field = -> 
    $('#other_system_text').focus(-> $('#other_system_radio').attr('checked','checked')) 
    $('#other_system_text').keyup(-> $('#other_system_radio').val($(this).val()))