基于选中值显示/隐藏下拉菜单的实现问题
解决动态下拉列表显示/隐藏问题:仅选中"Yes"时显示第二个下拉菜单
原代码存在的问题
- 事件绑定不匹配:HTML中
onchange绑定的是showHideInput,但JS函数名为showHideOther1,导致选择变化时无法触发函数 - 选中状态判断错误:
selection1.selected不是正确的判断方式,应该通过选中选项的value或文本内容来判断 - 未定义变量:代码中直接使用
text变量,但未获取对应的DOM元素,会导致报错 - 初始状态未处理:页面加载时,第二个下拉菜单的显示状态未根据第一个下拉的默认选中值设置
修正后的完整代码
HTML 代码
<div class="smartcapture-controls"> <div class="sc-formfield-label"><label for="Dual_Nationality">Do you have dual nationality?</label></div> <div class="sc-formfield-input"> <select name="Dual_Nationality" id="optionOne" data-field-type="Text" required="required" data-validation-message="Please fill out this field." onchange="showHideOther1()"> <option value="1" selected="selected">Yes</option> <option value="No">No</option> </select> </div> </div> <div class="smartcapture-controls" id="optionTwo"> <div class="sc-formfield-label"><label for="Second_Nationality">Second_Nationality</label></div> <div class="sc-formfield-input"> <select name="Second_Nationality" id="secondNationality" data-field-type="Text" required="required" data-validation-message="Please fill out this field."> <option value="" selected="selected">Yes</option> <option value="No">No</option> </select> </div> </div>
JavaScript 代码
// 页面加载时初始化显示状态 window.onload = () => showHideOther1(); function showHideOther1() { const selection1 = document.getElementById("optionOne"); const optionTwoContainer = document.getElementById("optionTwo"); const secondSelect = document.getElementById("secondNationality"); // 匹配第一个下拉选中的"Yes"对应的value值(原HTML中Yes的value为"1") if (selection1.value === "1") { optionTwoContainer.style.display = "block"; secondSelect.required = true; } else { optionTwoContainer.style.display = "none"; secondSelect.required = false; } }
关键修正说明
- 统一事件与函数名:将HTML中的
onchange事件绑定改为与JS函数一致的showHideOther1() - 正确判断选中值:通过
selection1.value获取选中选项的value,原HTML中"Yes"对应的value是"1",以此作为判断依据 - 明确DOM元素引用:获取第二个下拉菜单的容器和内部的select元素,替代原代码中未定义的
text变量 - 初始化显示状态:添加页面加载事件,确保打开页面时第二个下拉菜单的状态与第一个下拉的默认选中值一致
- 移除冗余ID:删除选项上重复的
id="Yes"/id="No",避免页面ID冲突
内容的提问来源于stack exchange,提问作者JordanMiguel
相关产品推荐
相关产品推荐

