我正在尝试创建一个选项下拉菜单,当我尝试显示文本框时,如果选择了“其他”选项,我就会陷入困境。
这就是我所拥有的:
<span id="con-country"><label for="country">Country: </label>
<select name="country" required="required">
<option value="usa">United States</option>
<option value="uk">United Kingdom</option>
<option id="other" value="other">Other</option>
</select>
</span>
<span id="con-specify">
<label for="specify">Specify: </label>
<input type="text" name="specify" id="c-specify" required="required"></input>
</span>
CSS:
#con-specify{
margin-left: 50px;
display: none;
}
简单吧?问题是我不知道如何在jQuery中执行代码
因此,如果用户在菜单中选择其他,则应显示文本框,我该怎么做?
答案 0 :(得分:1)
尝试
//dom ready handler
jQuery(function($){
//change event handler for the select
$('select[name="country"]').change(function(){
//set the visibility of the specify element based on the value of select
$('#con-specify').toggle(this.value == 'other')
}).change();//fire the change event so that the initial visibility is set
})
演示:Fiddle
中的每种方法答案 1 :(得分:0)
如果您已经使用过jQuery,只需使用$('#con-specify').show()
和$('#con-specify').hide()
答案 2 :(得分:0)
您需要在html的头部添加一个jQuery链接:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
下拉菜单应该有一个ID(即:国家/地区)。
然后你的javascript看起来像这样:
window.onload = function() {
$('#con-specify').hide();
$('#country').change(function(){
if($(this).val() == 'other') {
$('#con-specify').show();
} else {
$('#con-specify').hide();
}
});
};