2011-06-02 33 views
0

我在我的軌道形成如下代碼:軌形成 - 2場與形式相同的ID - 如何禁用第二場時選擇的第一場

<label>Fruit: </label> <%= f.select(:IST_FRUIT, [['Apple', 'Apple'], 
          ['Orange', 'Orange'], 
          ['Kiwi', 'Kiwi'], 
          ['Other', 'Other'] 
          ],{ :prompt => "Please select"},{:onchange => "if (this.value == 'Other') 
                     {document.getElementById('otherTissue').style.display = 'block'; 
                     } "} 
         ) %> 

<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :IST_FRUIT, :size => 10 %></span> 

用戶可以選擇果形列表框中但如果用戶選擇「其他」,則會顯示一個文本字段以允許用戶輸入其值。

問題是,當用戶選擇一個水果並保存表單時,表中空白的水果字段和原因是表單正在保存ID爲'IST_FRUIT'的跨度中找到的第二個字段'IST_FRUIT' 。

如果有人能夠向我展示如何在未選擇「其他」時禁用第二個字段,並在從其下拉列表中選擇「其他」時啓用它,我將不勝感激。

許多非常感謝您提供的任何建議。

回答

1

首先,請注意,rails的帖子是根據字段的名稱而不是id。

對於您的情況,您應該使用virtual attribute來存儲潛在的other fruit值。

您的模型可能看起來像:

attr_accessor :other_fruit 

before_save :check_fruits 

def check_fruits 
    #if other_fruit is not nil, it means that you want to store it's value in you IST_FRUIT column 
    #BTW, why these capital letters? 
    IST_FRUIT = other_fruit unless other_fruit.nil? 
end 

和你的形式是:

<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :other_fruit, :size => 10 %></span> 
+0

你好,非常感謝你的建議。我在我的水果模型中添加了「def check_fruits」函數,現在出現以下代碼行'IST_FRUIT = other_fruit,除非other_fruit.nil? - 它說動態不斷分配錯誤 ' – tanya 2011-06-02 12:18:18

+0

'table'的名字是什麼?這是'IST_FRUIT'還是更可能是'ist_fruits'? – apneadiving 2011-06-02 12:26:45

+0

明白了 - 更改'IST_FRUIT = other_fruit除非other_fruit.nil? 'to'self [:IST_FRUIT] = other_fruit除非other_fruit.blank? – tanya 2011-06-02 12:56:12

1

我還有一個忠告。而不是禁用HTML輸入(順便說一句 - 在HTML文檔中ID必須是唯一的),只需在模型中創建另一個屬性,例如將其命名爲「other_fruit」,如果「水果」設置爲「其他「或是空的。例如,你可以寫這樣的東西:

class TheModel 
    attr :other_fruit 

    # Overwritten accessor for the fruit attribute. 
    # Returns the values of :other_fruit if :fruit is blank. 
    # 
    def fruit 
    if self[:fruit].blank? 
     other_fruit 
    else 
     self[:fruit] 
    end 
    end 
end 

現在的HTML部分。在您的JavaScript中,您將「顯示」設置爲阻止,但在用戶選擇另一個選項時不會重置。

如果要防止將字段發送到服務器,應設置'disabled'屬性。設置'風格'只隱藏用戶眼中的控制。