Radio Button Property Verified

On my page, I have three radio buttons, and I want to check the radio buttons when I click on <li> . My click function works, but when I click the radio is not checked. How can i do this? My code is below

 $(document).ready(function() { $('#myContainer li').click(function() { $('#radio1').attr('checked'); }); }); <div id="myContainer"> <li id="li1"> <input id="radio1" name="RadioGroup" value="val1" type="radio"> val1 </li> <li id="li2"> <input id="radio2" name="RadioGroup" value="val2" type="radio"> val2 </li> <li id="li3"> <input id="radio3" name="RadioGroup" value="val3" type="radio"> val3 </li> </div> 
+4
source share
2 answers

You get the checked attribute instead of setting it. Try instead:

 $('#radio1').attr('checked', 'checked'); 

Note

Since jQuery 1.6, it is recommended to use .prop() instead of .attr() .

 $("#radio1").prop("checked", true); 
+12
source
 $('#radio1').attr('checked')' 

will return you a value to set the try value

 $('#myContainer li').click(function() { $('#radio1').attr('checked','checked'); }); 

or if you are using jquery 1.6+, use prop

 $('#myContainer li').click(function() { $('#radio1').prop('checked',true); }); 

DMEO

in your case no matter which li you click, it will check the radio with id = #radio1


in my opinion a more appropriate behavior would be

 $('#myContainer li').click(function() { $(":input",this).prop('checked',true); }); 

Demo

+2
source

Source: https://habr.com/ru/post/1403447/


All Articles