Javascript 仅在选择特定选项时才显示输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29321494/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:10:41  来源:igfitidea点击:

Show input field only if a specific option is selected

javascripthtmlformshtml-select

提问by user1589375

I'm trying to make a form which checks if a certain option is selected from a "select" tag. Here is my current HTML:

我正在尝试制作一个表单,用于检查是否从“选择”标签中选择了某个选项。这是我当前的 HTML:

<select onchange="yesnoCheck()">
    <option id="noCheck" value="">Valitse automerkkisi</option>
    <option id="noCheck" value="lada">Lada</option>
    <option id="noCheck" value="mosse">Mosse</option>
    <option id="noCheck" value="volga">Volga</option>
    <option id="noCheck" value="vartburg">Vartburg</option>
    <option id="yesCheck" value="other">Muu</option>
</select>

This is the div element which should become visible after "Muu" is selected:

这是选择“Muu”后应该变得可见的 div 元素:

<div id="ifYes" style="display: none;">
    <label for="car">Muu, mik??</label> <input type="text" id="car" name="car" /><br />
</div>

And here is the JavaScript I'm trying to use:

这是我尝试使用的 JavaScript:

<script type="text/javascript">
    function yesnoCheck() {
        if (document.getElementById("yesCheck").checked) {
            document.getElementById("ifYes").style.display = "block";
        } else {
            document.getElementById("ifYes").style.display = "none";
        }
    }
</script>

But it's not working...

但它不起作用...

回答by Josephus87

here you go:

干得好:

function yesnoCheck(that) {
    if (that.value == "other") {
  alert("check");
        document.getElementById("ifYes").style.display = "block";
    } else {
        document.getElementById("ifYes").style.display = "none";
    }
}
<select onchange="yesnoCheck(this);">
    <option value="">Valitse automerkkisi</option>
    <option value="lada">Lada</option>
    <option value="mosse">Mosse</option>
    <option value="volga">Volga</option>
    <option value="vartburg">Vartburg</option>
    <option value="other">Muu</option>
</select>

<div id="ifYes" style="display: none;">
    <label for="car">Muu, mik??</label> <input type="text" id="car" name="car" /><br />
</div>

回答by Mike

Check out: Display div if a specific select option value is selected

签出:如果选择了特定的选择选项值,则显示 div

Also don't use ID use data attributes or value to check comparison.

也不要使用 ID 使用数据属性或值来检查比较。