简体   繁体   中英

Radio buttons in the form, if one checked then unchecked the others?

I have three different group of radio buttons in my form. If I click on the radio button I don't see attribute checked set to true. I'm wondering what is the best way to handle this in JQuery/JavaScript? Here is example:

 $("input[type=radio]").on('click', function() { var secondClick = true; $(this).change(function() { secondClick = false; }); $(this).click(function() { if (secondClick) { $(this).prop("checked", false); } secondClick = true; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="myForm" id="myForm" method="POST" action="#"> <div class="formItem"> <label for="evaluation">Evaluation</label> <input type="radio" name="frm_eval" id="frm_eval1" value="0" />Yes <input type="radio" name="frm_eval" id="frm_eval2" value="1" />No </div> <div class="formItem"> <label for="conditions">Conditions</label> <input type="radio" name="frm_cond" id="frm_cond1" value="0" />Good <input type="radio" name="frmhs_cond" id="frm_cond2" value="1" />Fair <input type="radio" name="frm_cond" id="frm_cond3" value="2" />Poor </div> <div class="formItem"> <label for="responses">Responses</label> <input type="radio" name="frm_res" id="frm_res1" value="0" />Good <input type="radio" name="frm_res" id="frm_res2" value="1" />Fair <input type="radio" name="frm_res" id="frm_res3" value="2" />Poor </div> </form> 

Function above did not change/set the attribute checked=true on the element that I clicked. I would like to see selected element with an attribute checked true and all other check boxes to be set to false.

Your second input in conditions was named frmhs_cond instead of frm_cond

 <form name="myForm" id="myForm" method="POST" action="#"> <div class="formItem"> <label for="evaluation">Evaluation</label> <input type="radio" name="frm_eval" id="frm_eval1" value="0" />Yes <input type="radio" name="frm_eval" id="frm_eval2" value="1" />No </div> <div class="formItem"> <label for="conditions">Conditions</label> <input type="radio" name="frm_cond" id="frm_cond1" value="0" />Good <input type="radio" name="frm_cond" id="frm_cond2" value="1" />Fair <input type="radio" name="frm_cond" id="frm_cond3" value="2" />Poor </div> <div class="formItem"> <label for="responses">Responses</label> <input type="radio" name="frm_res" id="frm_res1" value="0" />Good <input type="radio" name="frm_res" id="frm_res2" value="1" />Fair <input type="radio" name="frm_res" id="frm_res3" value="2" />Poor </div> </form> 

 var radioInputs = $("#myForm input[type=radio]") radioInputs.on('change',function() { var $this = $(this) if ($this.is(':checked')) { radioInputs.not($this).removeAttr('checked') } }) 

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