【问题标题】:on select display textbox with jquery?在使用 jquery 选择显示文本框?
【发布时间】:2011-01-19 21:12:05
【问题描述】:

我确定这非常简单,但我似乎不认为我做错了什么,无论如何我的表单有一个“标题”选择列表,如果“其他”我想显示一个文本框" 被选中。

<select name="title" id="title" class="required">
    <option value="" selected="selected">- Select Title -</option>
    <option value="Ms.">Ms.</option>
    <option value="Mrs.">Mrs.</option>
    <option value="Mr.">Mr.</option>
    <option value="Dr.">Dr.</option>
    <option value="Prof.">Prof.</option>
    <option value="Rev.">Rev.</option>
    <option value="Other" onclick="showOther();">Other</option>
</select>

function showOther() {
  jQuery("#otherTitle").show();
}

但这不起作用..当页面加载时,#otherTitle 文本框使用 jquery 隐藏。

【问题讨论】:

    标签: jquery forms select


    【解决方案1】:

    我会建议一种不同的方法:

    $("#title").change(function() {
        if($(this).find("option:last").is(':selected')) {
            $("#otherTitle").show();
        } else {
            $("#otherTitle").hide();
        }
    });
    

    也就是说,如果选择了 last 选项,则显示 ID 为 otherTitle 的文本框。我实际上使用这种方法。希望有帮助。当然,您的 'Other' 字段必须始终放在最后才能使用 - 而且它对于多语言网站非常方便。

    【讨论】:

      【解决方案2】:
      1. 使用 jQuery 来绑定您的事件处理程序,而不是使用“onfoo”元素属性
      2. 您最好将处理程序绑定到“select”元素,因为有些方法可以选择不涉及“click”事件的选项:

      (一些文字让stackoverflow显示下面的代码块)

      $(function() {
        $('#title').change(function() {
          if ($(this).val() == 'Other')
            $('#otherTitle').show();
          else
            $('#otherTitle').hide();
        });
      });
      

      我更愿意给“其他”选项一个“id”值而不是依赖于“值”,但无论如何。

      【讨论】:

        【解决方案3】:

        将一个事件绑定到您的选择列表,当它发生变化时,查看该值并进行隐藏/显示

        $(function(){
        
            $("#title").change(function () {
                if ($(this).val() == 'Other') {
                    $("#otherTitle").show();
                }
            });
        
        });
        

        【讨论】:

          【解决方案4】:
          $(function() {    
              $('#title').change(function() {
                if (this.value === "Other") {
                  $("#otherTitle").show();
                }
                else {
                  $("#otherTitle").hide();
                }     
              });    
          });
          

          和一个 Working Demo。添加 /edit 到 url 以查看代码

          【讨论】:

            猜你喜欢
            • 2013-08-28
            • 2011-01-31
            • 1970-01-01
            • 1970-01-01
            • 2014-05-12
            • 2012-03-16
            • 2011-05-31
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多