如何根据下拉列表隐藏输入



我有一个登录表单,用户可以从下拉列表中选择他们的国家/地区,只有当用户从下拉菜单中选择"其他"时,我才想显示"如果其他指定"选项。

我已经找到了这个问题的许多其他答案,但它们使用的是jQuery,我希望使用纯JavaScript。

这是我的HTML代码。

<form>
Username/Name:<br><input type="text"><br>
Country:<br>
<select id="country" name="country">
<option value="us">United States   </option>
<option value="uk">United Kingdom  </option>
<option value="ca">Canada  </option>
<option value="othr">Other  </option>
</select><br>
If other specify:<br><input type="text"><br>
Password:<br><input type="text"><br>
<input type="submit" value="Log In">
</form>

谢谢!

修复othr到other的拼写错误。

将你想显示/隐藏的东西包装在ID为"其他容器"的元素中,然后

function handleCountryChange(event) {
var display = event.target.value == 'other' ? 'inline' : 'none';
otherContainer.style.display = display;
}
var otherContainer = document.getElementById('other-container');
var countrySelect = document.getElementById('country');
countrySelect.addEventListener('change', handleCountryChange)

最新更新