jQuery radio onchange toggle class of parent element?

TigerTiger picture TigerTiger · Jun 8, 2009 · Viewed 52.4k times · Source

Please have a look on the following:

$('#myRadio').change(function() {           

    if($(this).is(':checked'))  {
        $(this).parent().addClass('green');
    } else {                              
        $(this).parent().removeClass('green');
    }
});

Markup lookslike somewhat as following

<table>
  <tr>
    <td>Some text 1 </td>
    <td><input type="radio" value="txt1" name="myRadio" id="text1" /></td>
    <td>Some text 2 </td>
    <td><input type="radio" value="txt2" name="myRadio" id="text2" /></td>
    <td>Some text 3 </td>
    <td><input type="radio" value="txt3" name="myRadio" id="text2" /></td>
  </tr>
</table>

When I switch radio, above javascript code applies 'green' to TD tag, which is fine. But if I change the selection to another it adds the green to another but doesnt remove the green from the previously selected radio.

How do I make it work so that selecting a radio option changes its parent TD's class to green and selecting another will reset all but add green to only the newly selected!

Can it also be made to change class of its first previous TD which contains "some text 3" etc??

Thanks.

Answer

Chris Van Opstal picture Chris Van Opstal · Jun 8, 2009

Try something like this:

if($(this).is(':checked'))  {
    $(this).parent().parent().parent().find('.green').removeClass('green');
    $(this).parent().addClass('green');
}

This will find the table element of your current radio button grouping, find any elements with the green class, and remove the class.

Alternatively, if you only have one radio button group on the page, it would be simpler to just do:

$('.green').removeClass('green');