The radio button is checked by default when the page loads. I want the label that wraps around this radio button to have a CSS class added to it.
What's wrong with my code?
JSFIDDLE: http://jsfiddle.net/3ar43086/4/
$(document).ready(function() {
if ($('input[type=radio]').is(':checked')) {
$(this).parent('label').addClass('checked'); }
});
<label for="myRadio"><input type="radio" id="myRadio" value="Example Radio Button" name="amount" checked>Example Radio Button</label>
.checked { background: yellow; }
$(this)
in your code refers to document
instead of the input
.
This fixes it:
$(document).ready(function() {
if ($('input[type=radio]').is(':checked')) {
$('input[type=radio]').parent('label').addClass('checked');
}
});
You could also do it like this:
$(document).ready(function() {
$('input[type=radio]:checked').parent('label').addClass('checked');
});
this
in the following line refers to window
$(this).parent('label').addClass('checked');
You should do this instead:
$(document).ready(function() {
var myInput = $('input[type=radio]');
if (myInput.is(':checked')) {
myInput.parent('label').addClass('checked'); }
});
Or, if you want to treat all the input
on your page:
$(document).ready(function() {
$('input[type=radio]').each(function(){
if ($(this).is(':checked')) {
$(this).parent('label').addClass('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.