简体   繁体   中英

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 --> 

 $(document).ready(function(){ $("[type=checkbox]").change(function(){ if (!($("#norA").is(":checked") && $("#norB").is(":checked"))) { $("#nors").html("on");} else {$("#nors").html("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> 

 if($("#norA").is(":checked") && $("#norB").is(":checked")){
    $("#nors").html("off");
        }
 else{ 
   $("#nors").html("on");
       }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM