在复选框单击上切换突出显示

时间:2015-07-21 15:37:32

标签: javascript jquery html

对于下表:

<table id="a_grid">
  <tr id="a_row">
    <td>Choice A<input type="checkbox" id="a_box" class="box"></td>
    <td>Reason:<input type="text" id="a_text" class="reason"></td>
  </tr>
  <tr id="b_row">
    <td>Choice B<input type="checkbox" id="b_box" class="box"></td>
    <td>Reason:<input type="text" id="b_text" class="reason"></td>
  </tr>
</table>

我正在努力使其工作,当您单击复选框时,它会将“控件”类切换到其具有特定颜色的相应文本框。尝试按类识别,以便我可以扩展表。

我尝试了什么:

 $(".box").change(function () {
   $(".reason").toggleClass("control", false);
 });

1 个答案:

答案 0 :(得分:1)

  • 您当前定位的所有复选框都带有.reason,而您需要使用事件附带的上下文,I.E。复选框本身。从那里你可以遍历到行,然后到达输入。
  • .toggleClass()将始终删除该类,因为您将false作为第二个参数传递。然后,您可以使用.checked属性
  • 基于复选框切换类
$('.box').change(function(){
  var $this = $(this);
  $this.closest('tr').find('.reason')
         .toggleClass('control', $this.prop('checked'));
});

JSFiddle

相关问题