Mike Mike - 2 months ago 6
HTML Question

How to add a class to each TD in a TR when the TR gets selected

I am using HTML, PHP and JS to create a report website. I've got several table that I'm showing. In each table there are multiple rows

tr
with many columns
td
. I have it setup so that when I click on one of the
tr
it gets the class of
selected
. I also have it setup so that the
td
that is clicked in gets the class of
selectedtd
. What I want is to have all the
td
in the
tr
that gets selected to have the class
selectedtd
and then to have that class removed when the
tr
is unselected. Here's what I've got so far:

This script updates the
tr
to either have the class or remove it when anywhere in the
tr
is clicked.

<script type='text/javascript'>//<![CDATA[
$("#UpdateTable tr").click(function ()
{
$(this).toggleClass('selected').siblings().removeClass('selected');
});
//]]>
</script>


This script adds or removes the class
selectedtd
to an individual
td
when it is clicked.

<script type='text/javascript'>//<![CDATA[
$("#UpdateTable td").click(function ()
{
$(this).closest('table').find('td').not(this).removeClass('selectedtd');
$(this).toggleClass('selectedtd')
});
//]]>
</script>


I can't figure out how to get these to update all the
td
in the selected
tr
to have the class
selectedtd
.

Answer

As required tr is already selected, just use .find() to select the td's within the selected tr.

Try below code.

<script type='text/javascript'>
  //< ![CDATA[
  $(function() {
    $("#UpdateTable tr").click(function() {
      $(this).toggleClass('selected').find('td').toggleClass('selectedtd');
    });
  });
  //]]>
</script>

Complete Example:

td.selectedtd {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type='text/javascript'>
  //< ![CDATA[
  $(function() {
    $("#UpdateTable tr").click(function() {
      $(this).toggleClass('selected').find('td').toggleClass('selectedtd');
    });
  });
  //]]>
</script>

<table id="UpdateTable">
  <tr>
    <td>Some text</td>
    <td>Some text</td>
    <td>Some text</td>
  </tr>
  <tr>
    <td>Some text</td>
    <td>Some text</td>
    <td>Some text</td>
  </tr>
  <tr>
    <td>Some text</td>
    <td>Some text</td>
    <td>Some text</td>
  </tr>
  <tr>
    <td>Some text</td>
    <td>Some text</td>
    <td>Some text</td>
  </tr>
</table>

Comments