基于选择框选择显示/隐藏文本字段

时间:2012-12-17 23:56:48

标签: jquery ruby-on-rails ruby-on-rails-3

以简单的形式:

<%= 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_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>

4 个答案:

答案 0 :(得分: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文件中

答案 1 :(得分:1)

替换

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

答案 2 :(得分:0)

应该是$("#user_source")

Rails在属性之前添加模型名称。然后它应该隐藏/显示$("#user_source_other")元素。

此外,您必须将此jQuery JS代码包装在$(document).ready()$(function(){});中,因为charlietfl之前已回答过。

答案 3 :(得分:0)

 $(document).on("change", "#user_source", function(){
    var value = $(this).val();
    if (value === "Other"){
      $("#source_other").show();
    }else{
      $("#source_other").hide();
    }
  })
相关问题