0
votes

I'm trying to write a simple script where there are two sets of radio buttons, with True and False values. The idea is to display "true" if both True buttons are selected, and "false" if one of the buttons selected is False. No matter the input though, the result always displays as "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>

I'm at my wits' end here. I've even made sure to display the radio1 and radio2 values through the if statement and sure enough, it will still display "True" when either either radio1 or radio2 have a value of false. How is this possible?

2
do you want false if both are false also?Chris L

2 Answers

2
votes

The radio button values are not booleans, they're strings, and non-empty strings evaluate to true in JavaScript. They're considered to be truthy values.

You can use a strict comparison:

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

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

Robby answered as I was putting together my answer. So yes you gave the variables string values and your if needs to compare multiple conditions:

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