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>
4

4 回答 4

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 之后加载的外部文件中

于 2012-12-18T00:03:43.220 回答
1

代替

 $("#source") with $("#user_source")
于 2012-12-19T10:56:05.230 回答
0

应该$("#user_source")改为!

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

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

于 2012-12-18T15:31:44.470 回答
0
 $(document).on("change", "#user_source", function(){
    var value = $(this).val();
    if (value === "Other"){
      $("#source_other").show();
    }else{
      $("#source_other").hide();
    }
  })
于 2020-08-22T18:53:10.080 回答