Reputation: 5074
So I have an HTML table populated with negative and positive values. I want to query the specific values and then upon hovering over the table values less than 0 I want to highlight the row with a red background color and for values greater than or equal to 0 should highlight with a blue background.
My current attempt is:
$(document).ready(function(){
var rows = $("#htmlTable").find('tbody').find('tr');
$.each(rows, function(key, value){
var rowData = $(rows[key]).find('td:eq(1)').html();
if (rowData < 0) {
$("tr").hover(function(){
$(this).addClass('.table-style-1 tbody > tr:hover');
}
}
else {
$("tr").hover(function(){
$(this).addClass('.table-style-2 tbody > tr:hover');
});
}
});
});
The CSS classes are as follows:
.table-style-1 tbody > tr:hover {
background-color: red;
}
.table-style-2 tbody > tr:hover {
background-color: blue;
}
My above code is correctly getting the data from the table as can been seen with a simple console.log(rowData)
line so I am assuming that my problem is with my implementation of addClass()
and hover()
functions. The console isn't showing any syntax errors but the table has no highlight functionality upon hovering. Any help would be greatly appreciated.
Upvotes: 3
Views: 2427
Reputation: 8539
here is an example: http://jsfiddle.net/wgkf4o9j/
$(document).ready(function(){
$('table').on('mouseover','tr',function(event){
var $tr = $(event.currentTarget);
$tr.parents('table').find('td').removeClass('blue red');
var value = parseInt($tr.find('td:eq(1)').html());
$tr.find('td').addClass(value < 0?'red':'blue');
})
});
Upvotes: 3
Reputation: 123377
Since you're getting a string with rowData = $(rows[key]).find('td:eq(1)').html();
you shoud cast the value into an integer when you do a comparison, e.g.
if (parseInt(rowData, 10) < 0) { ...
Also why exactly are you adding a class like .table-style-2 tbody > tr:hover
? You should just add the a class to the rows e.g. negative
or positive
(note: you need to use $(this)
and not $('tr')
)
if (parseInt(rowData, 10) < 0) {
$(this).addClass('negative');
}
else {
$(this).addClass('positive');
}
and define your css like so
tr.negative:hover {
background-color: red;
}
tr.positive:hover {
background-color: blue;
}
Upvotes: 4