我需要两个下拉菜单,当从任一菜单中选择"其他"时,会出现一个文本框,允许用户键入他们的答案。
我可以创建两个下拉菜单,并可以让其中一个打开文本框,但我似乎无法让两个都完成相同的操作。我已经尝试了很多选择,但无法让它工作。任何人都可以帮忙。
谢谢
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('association');
var optOtherReason = document.getElementById('association_detail');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 5) {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
</head>
<body>
<p>
<label>Stakeholder association (How you are affiliated with EMWIN):</label>
<select id = "association" name="association" >
<option value="na">Select:</option>
<option value="AR">Academic Research</option>
<option value="EM">Emergency Management</option>
<option value="EV">Equipment Vender</option>
<option value="RB">Re-broadcast</option>
<option value="Other">Other</option>
</select>
</p>
<div id="association_detail" style="display: none;">
<input id="namesignup" name="namesignup" required="required" type="text" placeholder="How you are affiliated with EMWIN" />
</div>
<p>
<label>Stakeholder association (How you are affiliated with EMWIN):</label>
<select id = "select_use" name="select_use" >
<option value="na">Select:</option>
<option value="sat">Satellite</option>
<option value="int">Internet</option>
<option value="vhf">VHF Radio Rebroadcast</option>
<option value="Other">Other</option>
</select>
</p>
<div id="Use" style="display: none;">
<input id="namesignup" name="namesignup" required="required" type="text" placeholder="How you are affiliated with EMWIN" />
</div>
</body>
</html>
我注意到的一些问题:
- 您的"其他"文本框具有相同的 ID/名称;这不符合 HTML 标准。您需要确保每个元素都有一个唯一的 ID。
- 你只听
eSelect
的变化;如果你还想切换Use
div的可见性,你需要监听select-use
何时变化(即你需要构造另一个处理程序)。
您需要获取第二个选择框(id="select_use"),并向其添加另一个onchange处理程序。在第二个 onchange 处理程序中,您需要选择第二个文本框 (id="use") 来显示/隐藏它。
下面是代码的更新版本:
var eSelect = document.getElementById('association');
var eSelect2 = document.getElementById('select_use');
var optOtherReason = document.getElementById('association_detail');
var optOtherReason2 = document.getElementById('Use');
eSelect.onchange = function() {
if(this.options[this.selectedIndex].value === 'Other') {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
eSelect2.onchange = function() {
if(this.options[this.selectedIndex].value === 'Other') {
optOtherReason2.style.display = 'block';
} else {
optOtherReason2.style.display = 'none';
}
}
在这里试试:https://jsfiddle.net/ve9fg0tc/2/
同样在您的 onchange 处理程序中,最好根据所选值("其他")而不是索引显示/隐藏文本框。这是因为您将来可能会在菜单中添加/删除更多项目,因此索引将更改并且条件将不再有效。