Mohsen Sabbaghi Mohsen Sabbaghi - 7 months ago 10
Javascript Question

Checked and change radio button in one group name

I have a table that has a radio button with the same "name" attribute as a row selector in each row.

There is simple JQuery code that selects the checked radio button and finds the

<tr>
tag and then highlights it by css, the problem is: when I change the radio button from another table row's, new rows gets the style but previous row are still highlighted! here is my HTML:



$('.my-table input').click(function() {
var checked = $(this).attr('checked', true);
if (checked) {
$(this).closest('tr').addClass("highlighted");
} else {
$(this).closest('tr').removeClass("highlighted");
}
});

.highlighted {
background-color: lightgreen;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="my-table">
<thead class="my-table-head">
<tr>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>
<input class="with-gap" name="group1" type="radio" id="rbtn2">
<label for="rbtn2"></label>
</p>
</td>
<td>title</td>

</tr>
<tr>
<td>
<p>
<input class="with-gap" name="group1" type="radio" id="rbtn3">
<label for="rbtn3"></label>
</p>
</td>
<td>titke2</td>

</tr>
<tr>
<td>
<p>
<input class="with-gap" name="group1" type="radio" id="rbtn4">
<label for="rbtn4"></label>
</p>
</td>
<td>title3</td>

</tr>
</tbody>
</table>




Answer

$('.my-table input').click(function() {
        $(this).closest('tbody').find('tr').removeClass("highlighted");
        $(this).closest('tr').addClass("highlighted");
});
.highlighted {
  background-color: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="my-table">
  <thead class="my-table-head">
    <tr>
      <th>1</th>
      <th>2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <p>
          <input class="with-gap" name="group1" type="radio" id="rbtn2">
          <label for="rbtn2"></label>
        </p>
      </td>
      <td>title</td>

    </tr>
    <tr>
      <td>
        <p>
          <input class="with-gap" name="group1" type="radio" id="rbtn3">
          <label for="rbtn3"></label>
        </p>
      </td>
      <td>titke2</td>

    </tr>
    <tr>
      <td>
        <p>
          <input class="with-gap" name="group1" type="radio" id="rbtn4">
          <label for="rbtn4"></label>
        </p>
      </td>
      <td>title3</td>

    </tr>
  </tbody>
</table>