Reputation: 423
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
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);
});
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);
});
Upvotes: 2
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