基于选择框选择显示/隐藏文本字段 [英] Show/Hide Text Field Based on Select Box Selection

查看:112
本文介绍了基于选择框选择显示/隐藏文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以简单的形式:

<%= 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从源"字段中选择其他"值时仅显示源_其他"文本字段.根据我在网上看到的内容,看来我需要使用以下内容:

I am trying to learn how to use JQuery to only show the "source_other" text field when the value "Other" is selected from the "source" field. From what I've seen online, it looks like I need to use something like this:

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

但是,我不太了解如何将JQuery与我的表单集成在一起.有人可以指出正确的方向吗?

However, I am not quite understanding how to integrate the JQuery with my form. Could someone please point me in the right direction?

已更新:

这是生成的html代码段:

Here is the resulting html snippet:

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

推荐答案

我怀疑您的服务器代码未生成该元素的ID,在这种情况下,您的选择器正在寻找ID不存在的元素

I am suspecting that your server code doesn't generate an ID for the element, in which case your selectors are looking for elements with ID's that don't exist

如果是这种情况,请在服务器代码中添加一个ID,以便您的jQuery ID选择器可以使用,或者使用name=选择器

If that is the case either add an ID with your server code so your jQuery ID selectors will work or use name= selectors

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

    });
});

只要将jQuery代码包装在简写为$(document).ready()$(function(){});中,只要将jQuery库加载之后,就可以将其放置在脚本标记的页面中的任何位置.或者,您也可以将其放在jQuery之后加载的外部文件中

As long as jQuery code is wrapped in $(document).ready() or $(function(){}); which is shorthand for same, you can place it anywhere in page in a script tag so long as it is after after jQuery library has loaded . Or you can put it in extrnal file that loads after jQuery

这篇关于基于选择框选择显示/隐藏文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆