如果使用 jquery 选择下拉项,则显示表单字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18088381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show Form Field if Drop Down Item is Selected Using jquery
提问by rivitzs
I'm trying to create a dropdown field where if the "Other" item is selected, then a "Please Specify" text box appears. The below works with just one dropdown select field, but as soon as I add the second select field, it no longer works.
我正在尝试创建一个下拉字段,如果选择了“其他”项目,则会出现一个“请指定”文本框。以下仅适用于一个下拉选择字段,但一旦我添加第二个选择字段,它就不再起作用。
Here's what I have that doesn't seem to work:
这是我所拥有的似乎不起作用的东西:
CSS...
CSS...
#techother{display:none;}
#lmsother{display:none;}
Body...
身体...
<p>Chose Your Browser: <select name = "Browser" required>
<option value = "">-- Select an Option --</option>
<option value = "1">IE</option>
<option value = "2">FF</option>
<option value = "3">Safari</option>
<option value = "4">Opera</option>
<option value = "5">Other</option>
</select>
</p>
<div id="browserother">
<p>Please Specify: <label id="browserlabel"><input name="Other Browser" type="text" placeholder="Other Browser" size="50" /></label></p>
</div>
<p>Operating System: <select name = "OS" required>
<option value = "">-- Select an Option --</option>
<option value = "Win">Windows</option>
<option value = "ios">iOS</option>
<option value = "otheros">Other</option>
</select>
</p>
<div id="osother">
<p>Please Specify: <label id="oslabel"><input name="Other OS" type="text" placeholder="Other OS" size="50" /></label></p>
</div>
Script...
脚本...
<script>
$('form select[name=Browser]').change(function(){
if ($('form select option:selected').val() == '5'){
$('#browserother').show();
}else{
$('#browserother').hide();
}
});
$('form select[name=OS]').change(function(){
if ($('form select option:selected').val() == 'otheros'){
$('#osother').show();
}else{
$('#osother').hide();
}
});
</script>
Any way to make this work? Thanks!
有什么办法可以使这项工作?谢谢!
回答by David
Try this DEMO: http://jsfiddle.net/2pM3n/1/
试试这个演示:http: //jsfiddle.net/2pM3n/1/
$('select[name=Browser]').change(function () {
if ($(this).val() == '5') {
$('#browserother').show();
} else {
$('#browserother').hide();
}
});
$('select[name=OS]').change(function () {
if ($(this).val() == 'otheros') {
$('#osother').show();
} else {
$('#osother').hide();
}
});
回答by Alex
There you go: http://jsfiddle.net/ecZrE/
你去吧:http: //jsfiddle.net/ecZrE/
You mixed up some things in the selectors. Use
你在选择器中混淆了一些东西。用
$('p select[name=Browser]')
instead of
代替
$('form select[name=Browser]')
since there is no form element. But your snippet is incomplete anyway.
因为没有表单元素。但是无论如何,您的代码段都不完整。
Another wrong selector is
另一个错误的选择器是
$('form select option:selected')
because you forgot to specify the select element.
因为您忘记指定 select 元素。