user1077300
user1077300

Reputation: 423

radio button checked property

In my page I have three radio buttons and I want to checked the radio buttons when clicked to the <li>. My click function is working but when clicked the radio is not checked. How can I do that? 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>

Upvotes: 6

Views: 42192

Answers (2)

Rafay
Rafay

Reputation: 31033

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

will return you the value, inorder to set the value try

$('#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 more appropriate behavior would be

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

DEMO

Upvotes: 2

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You are getting the checked attribute instead of setting it. Try this instead:

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

Note

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

$("#radio1").prop("checked", true);

Upvotes: 19

Related Questions