Change color of table cell when radio button is ch

2019-08-08 23:22发布

问题:

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>

回答1:

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>



回答2:

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

Here is a fiddle



回答3:

$('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/