Razor303
Razor303

Reputation: 3

JQuery if td value < nothing change color of table row

I have a snipit of jquery that almost does what want, I want the row to change color not just the cell with the value.. can anyone help please been trying for hours

    $(document).ready(function() {
$('.nr2').filter(function(){
return $.trim($(this).text()) > '0'
}).css('background-color', '#24AD36');

});

fork on fiddle

Upvotes: 0

Views: 740

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

just chain the parent() method after the filter() to get the row

$(document).ready(function () {
    $('.nr2').filter(function () {
        return +($.trim($(this).text())) > 0
    }).parent().css('background-color', '#24AD36');

});

Example: http://jsfiddle.net/dpyu0mhq/1/


As a side note, I suggest to set a class instead of a css property , just to keep off style from javascript and make the code mantainance easier, e.g.

Javascript

.parent().addClass('highlight');

CSS

.highlight {
  background-color: #24AD36
}

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use closest() to find the nearest tr element. I would also suggest you convert the td value to an integer to compare against 0. Using greater than against strings can lead to some interesting results.

$('.nr2').filter(function () {
    return parseInt($.trim($(this).text()), 10) > 0
}).closest('tr').css('background-color', '#24AD36');

Updated fiddle

Upvotes: 0

Related Questions