选择单选按钮(多组)时突出显示行

时间:2018-09-26 16:27:38

标签: jquery html-table rows radio

我有一个表,其中包含多组单选按钮组。 当我突出显示单选按钮时,它会突出显示行。

下面的代码片段未考虑当我选择其他组时要保持突出显示该组的单选按钮的情况。

关于如何解决此问题的任何想法?

// highlight paragraphs for radio.
$(document).ready(function() {
  $('.record_table tr').click(function(event) {
    if (event.target.type !== 'radio') {
      $(':radio', this).trigger('click');
    }
  });

  $("input[type='radio']").change(function(e) {
    var rdname = $(this).attr('name');

    e.stopPropagation();
    $('.record_table tr').removeClass("highlight");
    if ($(this).is(":checked")) {
      $(this).closest('tr').addClass("highlight");
    }
  });
});
.highlight {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="record_table">
  <tr>
    <th>Set status</th>
  </tr>
  <tr>
    <td>active </td>
    <td> <input type='radio' id='123' name='group1'></td>
  </tr>
  <tr>
    <td>Not active </td>
    <td> <input type='radio' id='456' name='group1'></td>
  </tr>
  <tr>
    <th>Other Options</th>
  </tr>
  <tr>
    <td>active </td>
    <td> <input type='radio' id='412' name='group2'></td>
  </tr>
  <tr>
    <td>Not active </td>
    <td> <input type='radio' id='654' name='group2'></td>
  </tr>
  <tr>
    <th>3rd Options</th>
  </tr>
  <tr>
    <td>active </td>
    <td> <input type='radio' id='965' name='group3'></td>
  </tr>
  <tr>
    <td>Not active </td>
    <td> <input type='radio' id='963' name='group3'></td>
  </tr>
</table>

image of what i want

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的要求,则可以找到选中的单选并将类highlight添加到其父类tr

$('.record_table tr input:checked').closest('tr').addClass("highlight");

// highlight paragraphs for radio.
$(document).ready(function() {
  $('.record_table tr').click(function(event) {
    if (event.target.type !== 'radio') {
      $(':radio', this).trigger('click');
    }
  });

  $("input[type='radio']").change(function(e) {
    var rdname = $(this).attr('name');

    e.stopPropagation();
    $('.record_table tr').removeClass("highlight");
    $('.record_table tr input:checked').closest('tr').addClass("highlight");
  });
});
.highlight {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="record_table">
  <tr>
    <th>Set status</th>
  </tr>

  <tr>
    <td>active </td>
    <td> <input type='radio' id='123' name='group1'></td>
  </tr>
  <tr>
    <td>Not active </td>
    <td> <input type='radio' id='456' name='group1'></td>
  </tr>

  <tr>
    <th>Other Options</th>
  </tr>

  <tr>
    <td>active </td>
    <td> <input type='radio' id='412' name='group2'></td>
  </tr>
  <tr>
    <td>Not active </td>
    <td> <input type='radio' id='654' name='group2'></td>
  </tr>

  <tr>
    <th>3rd Options</th>
  </tr>

  <tr>
    <td>active </td>
    <td> <input type='radio' id='965' name='group3'></td>
  </tr>
  <tr>
    <td>Not active </td>
    <td> <input type='radio' id='963' name='group3'></td>
  </tr>