I am trying to implement a javascript which will highlight the column in an html table on click.As the below working example for row highlight i tried to use the same with t
Please try this:
$("#dataTable tr td").click(function() {
//Reset
$("#dataTable td").removeClass("highlight");
//Add highlight class to new column
var index = $(this).index();
$("#dataTable tr").each(function(i, tr) {
$(tr).find('td').eq(index).addClass("highlight");
});
});
.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="dataTable">
<tr><td>Data1</td><td>Data2</td></tr>
<tr><td>Data1</td><td>Data2</td></tr>
<tr><td>Data1</td><td>Data2</td></tr>
</table>
A fork Fisnik Tahiri solution to support also the tr selection (based on css or jquery if you preferir)
css:
.selected{ background-color: #ace; }
tr:hover{ background-color: #ace; }
Js:
$('td').on('mouseenter', function() {
var $currentTable = $(this).closest('table');
//var $row = $(this).closest('tr');
var index = $(this).index();
//clean
$currentTable.find('td').removeClass('selected');
//select row if you want use js
//$currentTable.find('tr').removeClass('selected');
//$row.addClass('selected');
//select column
$currentTable.find('tr').each(function() {
$(this).find('td').eq(index).addClass('selected');
});
});
working example
You can use the following code:
$('td').on('click', function() {
var $currentTable = $(this).closest('table');
var index = $(this).index();
$currentTable.find('td').removeClass('selected');
$currentTable.find('tr').each(function() {
$(this).find('td').eq(index).addClass('selected');
});
});
Just put this on your JS file and it will work on all available tables independently. In case you want to use it only on a specific table, just change the initial selector to $('#myTable td')
.
Also dont forget to add the .selected{ background-color: #ace; }
class in yor css file.
Here is the working example.
Cheers!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>onclick highlight</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$( ".table tr" ).click(function(){
$(".table tr" ).css("background-color","white");
$(this).css("background-color","green");
});
});
</script>
</head>
<body>
<table class="table">
<tr>
<td>Date1</td>
<td>Date2</td>
<td>Date3</td>
</tr>
<tr>
<td>Date1</td>
<td>Date2</td>
<td>Date3</td>
</tr>
<tr>
<td>Date1</td>
<td>Date2</td>
<td>Date3</td>
</tr>
</table>
</body>
</html>