简体   繁体   中英

Radio buttons changing class with jQuery

i have and issue with jQuery code for checking which one of the radio buttons is checked and then to change the color to some of them.Also i want to disable buttons after one of them is pressed. My problem i that when i check for example 'A' all the answers becoming red and not 'A' to become green and all the others red.

 $(function() { $('.AncientQ11 [type="radio"]').on('change', function() { $(document.getElementById("AncientQ1Ans1")).prev().addClass('green').siblings().addClass('red'); document.getElementById("AncientQ1Ans1").disabled = true; document.getElementById("AncientQ1Ans2").disabled = true; document.getElementById("AncientQ1Ans3").disabled = true; document.getElementById("AncientQ1Ans4").disabled = true; }); });
 .red {color: red;}.black {color: black;}.green{color:green;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="AncientQ11"> <label for="AncientQ1Ans1">A</label><br> <input type="radio" id="AncientQ1Ans1" name="AncientQ1"> <label for="AncientQ1Ans2">B</label><br> <!--Solution--> <input type="radio" id="AncientQ1Ans2" name="AncientQ1"> <label for="AncientQ1Ans3">C</label><br> <input type="radio" name="AncientQ1" id="AncientQ1Ans3"> <label for="AncientQ1Ans4">D</label> <input type="radio" name="AncientQ1" id="AncientQ1Ans4"> </div>

Removing br to use div with display:block; resolve your problem.

But after that if I select B,C or D solution, only the A is green. It's because you need to use $(this) to get the current element.

And I rewrite some parts to correspond to JQuery syntax like @freedomn-m suggests.

 $(function() { $('.AncientQ11 [type="radio"]').on('change', function() { $(this).prev().addClass('green').siblings().addClass('red'); $("#AncientQ1Ans1").attr("disabled", "disabled"); $("#AncientQ1Ans2").attr("disabled", "disabled"); $("#AncientQ1Ans3").attr("disabled", "disabled"); $("#AncientQ1Ans4").attr("disabled", "disabled"); }); });
 .red {color: red;}.black {color: black;}.green{color:green;}.AncientQ11 > div{ display:block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="AncientQ11"> <div> <label for="AncientQ1Ans1">A</label> <input type="radio" id="AncientQ1Ans1" name="AncientQ1"> </div> <div> <label for="AncientQ1Ans2">B</label> <input type="radio" id="AncientQ1Ans2" name="AncientQ1"> </div> <div> <label for="AncientQ1Ans3">C</label> <input type="radio" name="AncientQ1" id="AncientQ1Ans3"> </div> <div> <label for="AncientQ1Ans4">D</label> <input type="radio" name="AncientQ1" id="AncientQ1Ans4"> </div> </div>

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