无论输入如何,都显示相同的布尔结果

问题描述 投票:0回答:2

我正在尝试编写一个简单的脚本,其中有两组单选按钮,其值为True和False。想法是,如果两个True按钮均被选中,则显示“ true”;如果所选按钮之一为False,则显示“ false”。无论输入如何,结果始终显示为“ true”。

    <p>Select "True" or "False"</p>
    <form>
        <input type="radio" id="true1" name="bool1" value=true><br>
        <label for="true1">True</label><br>
        <input type="radio" id="false1" name="bool1" value=false><br>
        <label for="false1">False</label><br>
    </form>
    <p>Select "True" or "False" again</p>
    <form>
        <input type="radio" id="true2" name="bool2" value=true><br>
        <label for="true2">True</label><br>
        <input type="radio" id="false2" name="bool2" value=false><br>
        <label for="false2">False</label><br>
    </form>
    <input type="button" onclick="and()" value="Submit">
    <p id="and"></p>

<script>
    var radio1;
    var radio2;
    var result;
    function and(){
        try {
            radio1 = document.querySelector('input[name="bool1"]:checked').value;
            radio2 = document.querySelector('input[name="bool2"]:checked').value;
            if (radio1 && radio2)
            {
                document.getElementById("and").innerHTML = "True";
            }
            else
            {
                document.getElementById("and").innerHTML = "False";
            }
        }
        catch {
            alert("Select a checkbox on each form");
        }
    }
</script>

我在这里发挥了作用。我什至确保通过if语句显示radio1和radio2的值,并且足够肯定的是,当radio1或radio2的值为false时,它仍将显示“ True”。这怎么可能?

javascript html boolean-operations
2个回答
2
投票

单选按钮的值不是布尔值,它们是字符串,并且非空字符串在JavaScript中的值为true。它们被认为是truthy值。

您可以使用严格的比较:

radio = document.querySelector('input[name="bool1"]:checked').value;

if (radio === 'True') { /* ... */ } else { /* ... */ }

0
投票

罗比在回答我的时候回答。因此,是的,您为变量提供了字符串值,并且您的if需要比较多个条件:

var radio1;
 var radio2;
 var result;

 function and() {
   try {
     radio1 = document.querySelector('input[name="bool1"]:checked').value;
     radio2 = document.querySelector('input[name="bool2"]:checked').value;
     if ((radio1 == "true") && (radio2 == "true")) {
       document.getElementById("and").innerHTML = "True";
     } else {
       document.getElementById("and").innerHTML = "False";
     }
   } catch (err) {
     alert("Select a checkbox on each form");
   }
 }

jsFiddle

© www.soinside.com 2019 - 2024. All rights reserved.