【问题标题】:How to hide an input based on dropdown如何根据下拉菜单隐藏输入
【发布时间】:2018-11-02 23:18:44
【问题描述】:

我有一个登录表单,用户可以在其中从下拉列表中选择他们的国家,我想仅在用户从下拉列表中选择“其他”时才显示“如果其他指定”选项。

我已经找到了很多关于这个问题的其他答案,但他们使用的是 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>

谢谢!

【问题讨论】:

    标签: javascript forms input dropdown


    【解决方案1】:

    把othr的错别字改成other。

    将要显示/隐藏的内容包装在 ID 为“other-container”的元素中,然后

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 2012-08-06
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多