Even though you have already chosen Eddie's answer as the solution, I wanted to provide my own take on it.
In an effort to build upon his response, here is a code snippet that demonstrates how I would approach the task.
I urge you to pay attention to the JavaScript methods utilized in this code snippet, as that is the primary area where I have made modifications from Eddie's implementation. I have included comments within the code to enhance understanding.
Additionally, I injected some humor into the CSS!
// Adding event listener for checkbox changes within the table
$('.tb input[type="checkbox"]').change(function() {
// Removing the 'selected' class from all 'tr' and 'td' elements
$('.tb tr, .tb td').removeClass('selected');
// Applying the 'selected' class only to checked 'tr' (rows)
// The selection string can be directly placed inside the $() query without using the .find() method
$('.tb tr>td:first-child input[type="checkbox"]:checked').each(function() {
// Utilizing closest() instead of parent().parent() for better clarity and readability
$(this).closest('tr').addClass('selected');
})
// Applying the 'selected' class only to checked 'td' (columns)
var tds = $('.tb tr:first-child td');
$('.tb tr:first-child input[type="checkbox"]:checked').closest('td').each(function() {
// Styling selected 'tds' based on their index (+1 due to zero-based indexing)
$('.tb tr>td:nth-child(' + (tds.index($(this)) + 1) + ')').addClass('selected');
})
})
.tb {
font-size: 12px;
border: 1px solid #CCC;
font-family: Arial, Helvetica, sans-serif;
}
.tb td {
padding: 4px;
margin: 3px;
border: 1px solid #CCC;
}
.selected {
color: red;
}
/* Here's the fun part - styling intersections */
.selected .selected {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tb">
<tbody>
<!-- Table contents go here -->
</tbody>
</table>
Further information on .closest()
: https://api.jquery.com/closest/
More details on .index()
: https://api.jquery.com/index/
I trust this explanation proves beneficial to you.