Arkadij Arkadij - 6 months ago 9
Javascript Question

Javascript selecting and comparing checkboxes

title of this question seems to be pretty bad, I am sincerely sorry for that. I just couldn't come up with better phrasing.

I am trying to work on a "webapp" which allows the user to experiment with the logical operators like XOR, NOR and AND on a webpage. I am struggling with the programming though, especially with the NOR operator - which only works, if neither of my two checkboxes are checked.



iif ($("#norA").prop("checked") || $("#norB").prop("checked")) {
$("#nors").html("off");}
{$("#nors").html("on");}

<div class="row" id="options">
<div class="col-md-2"><div class="checkbox">
<label><input type="checkbox" name="nor" id="norA">A</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="nor" id="norB">B</label>
</div></div>

<div class="row" id="result">
<div class="col-md-2"><p id="nors">on</p></div></div> <!--placeholder of the solution/output -->




Answer

This code will handle the input and select the correct nor condition. Note that by separating the functional code from the event handler, you can also use it to set the initial condition, which this does.

$(document).ready(function() {
    $("input:checkbox").change(function() {
        toggleNors();
    });
    toggleNors();
})

function toggleNors() {
    var nor = !$("#norA").is(":checked") && !$("#norB").is(":checked")
    $("#nors").text(nor ? "on" : "off");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="options">
    <div class="col-md-2"><div class="checkbox">
        <label><input type="checkbox" name="nor" id="norA">A</label>
    </div>
    <div class="checkbox">
        <label><input type="checkbox" name="nor" id="norB">B</label>
    </div>
</div>

<div class="row" id="result">
    <div class="col-md-2">
        <p id="nors">on</p>
    </div>
</div>

The nor truth table is true if, and only if, neither a nor b are checked, and that's how this is implemented.