jQuery - radio buttons that add/remove a class to their labels
jquery
Solution
If you click on specific `input:radio` is always `checked`.
Use this instead:
$('input:radio').click(function() {
$('input:radio[name='+$(this).attr('name')+']').parent().removeClass('active');
$(this).parent().addClass('active');
});
`$('input:radio[name='+$(this).attr('name')+']')` selects all radio elements with the same name as clicked. Read about jquery selectors.
Fiddle: http://jsfiddle.net/NNkeQ/7/
Or just:
$('input:radio').click(function() {
$('label:has(input:radio:checked)').addClass('active');
$('label:has(input:radio:not(:checked))').removeClass('active');
});
http://jsfiddle.net/NNkeQ/18/
Problem
I know this may sound too easy for many but I just can't figure this one out on my own, I don't get what I'm missing. I have a set of radio buttons grouped in pairs. Each pair corresponds to an opt-in / opt-out section. What I need is to toggle a class `.active` on the `<label>`. Here's my basic HTML: ``` <td class="btn opt-in"> <label> <input type="radio" name="radio1" value="radio1"> </label> </td> <td class="btn opt-out"> <label> <input type="radio" name="radio1" value="radio2"> </label> </td> ``` Here's my JavaScript (it works partially): ``` $('input:radio').click(function() { if ($(this).is(':checked')) { $(this).parent().addClass('active'); } else { $(this).parent().removeClass('active'); }; }); ``` With the above script I'm able to add the class to the label just fine, but not remove/toggle it. Here's a Fiddle for reference. Any help is greatly appreciated.