Ryan Miller
Ryan Miller

Reputation: 315

Change color of table cell when radio button is checked

I would like for the cell neighboring my radiobutton's cell to be highlighted green when the radio button is checked, and to turn back to grey when it is moved to unchecked. In other words, the radio button containing the value of the winning team should turn the cell containing that team's name green.

$('input:radio').checked(function() {
  $(this).closest('td').addClass('highlight');
});
.highlight {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<tr id='game_1'>
  <td class='bowl'>Fiesta Bowl</td>
  <td id='radiocell'>
    <input type='radio' name=1 value='Arizona'></input>
  </td>
  <td class='team1'>Arizona</td>
  <td id='radiocell'>
    <input type='radio' name=1 value='Boise State'></input>
  </td>
  <td class='team2'>Boise State</td>
  <td class='gameDay'>January 1</td>
</tr>

Upvotes: 1

Views: 2268

Answers (3)

chrana
chrana

Reputation: 209

$('input:radio').change(function( event ) {
    $( "td" ).each(function() {
  $( this ).removeClass( "highlight" );
});
  $( event.target ).closest( "td" ).next("td").addClass("highlight");
});

Here is the working example
http://jsfiddle.net/6bc07guq/

Upvotes: 0

Barmar
Barmar

Reputation: 780899

The function to bind a handler is .click, not .checked. Then you need to update the classes of the TD's containing all the checkboxes.

$('input:radio').click(function() {
    $("input:radio").each(function() {
        $(this).closest("td").toggleClass("highlight", $(this).is(":checked"));
    });
});
.highlight {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr id='game_1'>
  <td class='bowl'>Fiesta Bowl</td>
  <td id='radiocell'>
    <input type='radio' name=1 value='Arizona'></input>
  </td>
  <td class='team1'>Arizona</td>
  <td id='radiocell'>
    <input type='radio' name=1 value='Boise State'></input>
  </td>
  <td class='team2'>Boise State</td>
  <td class='gameDay'>January 1</td>
</tr>
</table>

Upvotes: 1

rdubya
rdubya

Reputation: 2916

$('input:radio').change(function() {
    var $td = $(this).parent();
    $td.siblings().removeClass('highlight');
    $td.next().addClass('highlight');
});

Here is a fiddle

Upvotes: 2

Related Questions