2012-12-17 139 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")