Mike Mike - 4 months ago 17
Javascript Question

select and unselect td inside an HTML table

I have a table in my website that I want to be able to select one cell and the background color change, then select another cell (not in the same row) and have the first cell go back to the default color while the newly selected cell change background color. I've looked around and can only seem to find stuff that I've already got or something about a bunch of checkboxes. I have a Fiddle here.

Here's my CSS:

.selected {
background-color: rgba(0,0,0,0.4) !important;
color: #fff;
}


Here's my jquery:

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

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


Here's my HTML:

<body>

<table id='table'>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>Second Row</td>
<td>Still Second Row</td>
</tr>
</table>
<br><br>
<table id='table2'>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>Second Row</td>
<td>Still Second Row</td>
</tr>
</tbody>
</table>
</body>


I can get
table
to work fine selecting and unselecting rows, but
table2
doesn't work correctly. I select a cell in one row and then select a cell in the same row and it works, but if I select a cell in another row it does not change the first cell back to the default color. The fiddle above shows what is happening.

I tried adding a
<tbody>
, but I don't think that I did it correctly as the results did not change.

I tried adding
$('.selected').removeClass('selected');
and it partly worked. I can select a cell in one row then select a cell in another row and the background colors change correctly, but if I select the first cell a second time it does not unselect.

Answer

The way you select siblings for td is wrong, Try this

$("#table2 tbody td").click(function ()
{
  $(this).closest('table').find('td').not(this).removeClass('selected');  
  $(this).toggleClass('selected');
});

Fiddle

Comments