2010-02-22 58 views
1

我敢肯定,这是超级简单,但我似乎无法想象我做错了什么,无论如何,我有一个“标题”选择列表我的表单,我想显示一个文本框,如果“其他”被选中。在选择显示文本框与jQuery的?

<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当页面加载。

+0

谢谢大家:) – SoulieBaby 2010-02-22 23:49:33

回答

1
  1. 使用jQuery绑定你的事件处理程序,而不是“onfoo”元素的属性
  2. 你最好结合的处理程序,以“选择”的元素,因为有办法了该选项可以选择,这将不涉及“点击”事件:

(一些文本,使计算器显示下面的代码块)

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

我倒是PREF呃给“其他”选项一个“身份证”的价值,而不是依靠“价值”,但无论如何。

2

我会建议不同的方法:

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

也就是说,如果选择了最后选项,表明由ID otherTitle进入文本框。我实际上使用这种方法。希望有所帮助。当然,您的'其他'字段必须始终保持最后才能发挥作用 - 再加上它对于多语言网站来说非常方便。

1

绑定一个事件,您的选择列表中,当它改变时,看价值,做你的隐藏/显示

$(function(){ 

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

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

Working Demo。添加/编辑到url看到代码

相关问题