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>
Definition and Usage. The checked property sets or returns the checked state of a radio button. This property reflects the HTML checked attribute.
If a radio button is checked, its checked property is true . Then, we assign the value of the selected radio button to the selectedSize variable. Since only one radio button in a radio group can be checked at a time, the loop is terminated immediately by the break statement.
getElementById('id'). checked method for this. It will return the checked status of the radio button as a Boolean value. It can be either true or false.
To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true . When set to true , the radio button becomes checked and all other radio buttons with the same name attribute become unchecked. Here is the HTML for the examples in this article.
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);
$('#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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With