隐藏并显示基于其他选择值

时间:2017-12-14 11:15:05

标签: javascript

我有这个表单,有几个选择下拉列表,根据我们选择的内容,我们显示和隐藏其他下拉列表。当我选择值All时,geo选择会对所选值做出反应,但当我选择值Test时,function family选择不会消失。有什么理由吗?

选择“测试”时,我还需要将function family的值分配给0。帮助将不胜感激。

主要选择:

<select name="scope" onchange="javascript:sync_scope()">
                            <option value="1">All </option>
                            <option value="10">Test</option>
                        </select>

使用Javascript:

 function sync_scope() {
      var scope = document.form.scope.value;
      document.form.geo.style.display = ( scope == "1" ) ? "block" : "none";     
      document.form.function_family.style.display = ( scope == "10" ) ? "none" : "block";

    }

HTML

 <select name="geo">
    <?php foreach ($geos as $geo) : ?>
        <option value="<?php echo $geo['id']; ?>"><?php echo utf8_encode($geo['name']); ?></option>
    <?php endforeach; ?>
</select>

<select name="function_family" id ="function_family">
<option value="0" <?php selected($function_family, 0); ?>>All functions</option>
<?php foreach ($functions as $function) : ?>
    <option value="<?php echo $function['id']; ?>"><?php echo utf8_encode($function['name']); ?></option>
<?php endforeach; ?>
</select>

2 个答案:

答案 0 :(得分:1)

第二个选项中的if条件错误:

 function sync_scope() {
      var scope = document.form.scope.value;
      document.form.geo.style.display = ( scope == "1" ) ? "block" : "none";     
      document.form.function_family.style.display = ( scope == "10" ) ? "none" : "block";

    }

应该是:

 function sync_scope() {
      var scope = document.form.scope.value;
      document.form.geo.style.display = ( scope == "1" ) ? "block" : "none";     
      document.form.function_family.style.display = ( scope == "10" ) ? "block" : "none";

    }

要应用逻辑来选择特定值,只需执行以下操作:

document.form.function_family.value = 0;

当范围等于10.要添加它,你最好明确地写if而不是使用三元运算符:这样你检查一次范围的值并同时应用你想要的所有逻辑< / p>

答案 1 :(得分:0)

请试试这个,

<select id="mySelect" onchange="myFunction()">
    <option value="Audi">Audi
    <option value="BMW">BMW
</select>

<script>
    function myFunction() {
        var scope = document.getElementById("mySelect").value;
        if (scope == "Audi") {
            document.getElementById("geo").style.display = "block";     
            document.getElementById("function_family").style.display = "none";
        } else if (scope == "BMW") {
            document.getElementById("geo").style.display = "none";     
            document.getElementById("function_family").style.display = "block";
        }
    }
</script>

<select id="geo">
    <option value="1">1
    <option value="2">2
</select>
<select id="function_family">
    <option value="3">3
    <option value="4">4
</select>