Change color of table cell when radio button is checked

烈酒焚心 提交于 2019-12-24 12:37:25

问题


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/



来源:https://stackoverflow.com/questions/27663828/change-color-of-table-cell-when-radio-button-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!