2012-12-17 140 views
1

在一個簡單的形式:顯示/隱藏文本字段

<%= form_for @user do |f| %> 
    <%= f.label :source, "How did you find out about us?", :class => "control-label" %> 
    <%= f.select(:source, options_for_select([['-- Please select --',nil],['Source 1','Source 1'], ['Source 2','Source 2'], ['Other','Other']])) %> 

    <%= f.label :source_other, "Specify Other Source" %> 
    <%= f.text_field :source_other %> 
<% end %> 

我想學習如何使用jQuery,只顯示「source_other」文本字段當值「其他」是選自「源」字段。從我在網上看到,它看起來像我需要使用這樣的事情:

$("#source").change(function() { 
    if ($("#source").val()=="Other") 
    $("#source_other").show(); 
    else 
    $("#source_other").hide(); 
}); 

不過,我不太瞭解如何對jQuery和我的形式整合。有人能指點我正確的方向嗎?

更新時間:

這裏是生成的HTML片段:

<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post"> 
    <label class="control-label" for="user_lead_source">How did you find out about us?</label> 
    <select id="user_source" name="user[source]"><option value="">-- Please select --</option> 
    <option value="Source 1">Source 1</option> 
    <option value="Source 2">Source 2</option> 
    <option value="Other">Other</option> 
    </select> 

    <label for="user_source_other">Specify Other Source</label> 
    <input id="user_source_other" name="user[source_other]" size="30" type="text" /> 
</form> 
+0

請出示輸出HTML作爲瀏覽器發現。 「集成」意味着什麼? – charlietfl

+0

通過'integrate',我的意思是 - 我在哪裏放置JQuery代碼,以及爲了觸發它我還需要做些什麼。 – 2scottish

回答

2

我懷疑你的服務器代碼不生成的元素的ID,在這種情況下,你的選擇正在尋找爲ID的元素不存在

如果是這樣的情況下,或者添加一個ID與您的服務器代碼,以便您的jQuery的ID選擇將工作或使用name=選擇

$(function(){ 
    $('input[name="source"]').change(function() { 
     $('input[name="source_other"]').toggle( $(this).val()=="Other"); 

    }); 
}); 

只要jQuery代碼被包裹在$(document).ready()$(function(){});這是相同的簡寫,你可以在任何地方放置在網頁中的腳本標記,只要jQuery庫加載後它後。或者你可以把它放在jQuery加載的extrnal文件中

+0

嗯......看起來Rails爲輸入名稱「[User]」添加了一個前綴。我應該使用通配符還是類似的東西 - 確保我在JQuery代碼中引用正確的輸入名稱? – 2scottish

+0

OK ...看起來像rails添加了ID,所以原始代碼應該工作 – charlietfl

+0

我在我的View中使用了下面的代碼,但它仍然不能正常工作。我還缺少什麼?:'' – 2scottish

0

它應該是$("#user_source")而不是!

Rails在屬性前添加模型名稱。那麼它應該隱藏/顯示$("#user_source_other")元素。

而且,你必須在$(document).ready()$(function(){});作爲charlietfl面前回答這個包裹jQuery的JS代碼。

1

更換

$("#source") with $("#user_source")