0

I would like to hide <tr>'s based on background color of a <td> in the <tr>, my current code hides the <tr>'s based on the text in the <td> but that is not really a nice solution. The table is a calender so it would be nice if the JQuery could hide a table row based on background color.

My current code:

function ShowAbsence()
{
    if(!presenceActive) clearPresence();
    $('table#newspaper-a tr:not(#header, #trWeekNummer)').each(function() { 
        var toggle1 = true;
        $('td:not(#firstlastname)',this).each(function() { 
            if($(this).text() == "f" || $(this).text() == "M" || $(this).text() == "A") {
                toggle1 = false;
            }
        });
        if(toggle1) {
            $(this).toggle();
        }
    });

    if(absenceActive) {
        absenceActive = false; 
    } else {
        absenceActive = true;
    }
}

This works fine, but as you can see it hides based on the text in the cell. I hope you can help me hide it based on background color!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
BjornBogers
  • 98
  • 1
  • 1
  • 8

1 Answers1

1

You have to use the $.css() function of jQuery so you could get the color style associated with the selector.

This will return you an RGB value (like rgb(255,0.221) ), so in order to convert it to hexadecimal (of the type #ff00dd), you would need to use this function (extract from this other question):

function hexc(colorval) {
    var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    delete(parts[0]);
    for (var i = 1; i <= 3; ++i) {
        parts[i] = parseInt(parts[i]).toString(16);
        if (parts[i].length == 1) parts[i] = '0' + parts[i];
    }
    color = '#' + parts.join('');
    return color;
}

Therefor, you could so:

if (hexc($('#demo').css('background-color')) == '#ff00dd') {
    alert("Works!!");
}

Living example: http://jsfiddle.net/vyQKV/1/

BUT...

I would stronly recommend you to make use of classes rather than having to deal with the color. The background color should be defined with different classes and in order to check one you should just check the class with $.hasClass()

For example:

if($(this).hasClass('redBackground')){
    //whatever
}
Community
  • 1
  • 1
Alvaro
  • 40,778
  • 30
  • 164
  • 336