Reputation: 23593
My HTML has radio buttons inside their labels. I need to add a class to this label when the radio is selected, and remove the class when it is not.
My code below adds the class when the radio is selected but doesn't remove it when its unselected.
<div class="form-input radios"> <div class="form-radios form-element-type-radios"><div class="form-form-element-wrapper"><div class="form-item form-item-radio">
<div class="form-input radio"> <label class="option" for="edit-vehicle-owner-1"><input type="radio" name="vehicle_owner" value="1" class="form-radio form-element-type-radios"> Yes</label>
</div><div class="form-error"></div></div>
</div><div class="form-form-element-wrapper"><div class="form-item form-item-radio">
<div class="form-input radio"> <label class="option" for="edit-vehicle-owner-0"><input type="radio" value="0" class="form-radio form-element-type-radios"> No</label>
</div><div class="form-error"></div></div>
</div></div>
</div>
$('.form-element-type-radios').click(function(){
if ( $('input.form-radio').is(':checked') ) {
$(this).parent('label').addClass('checked');
}
else {
$(this).parent('label').removeClass('checked');
}
});
Upvotes: 3
Views: 1795
Reputation: 133403
You should use .change()
event
$('input.form-radio').change(function () {
if ($(this).prop('checked')) {
$('input.form-radio').parent('label').removeClass('checked')
$(this).parent('label').addClass('checked');
}
}).change();
Upvotes: 3
Reputation: 3792
Try doing that for all buttons using each function
$('.form-element-type-radios').click(function(){
$('input.form-radio').each(function(){
$(this).is(':checked') ? $(this).parent('label').addClass('checked') : $(this).parent('label').removeClass('checked');
})
});
Upvotes: 0