tags:

views:

64

answers:

2

After the user clicks on a table row, I want it to check if the table row's background-color is white, and if so, it will change the color to light blue.

The code I am using is not working. Here it is:

$("#tracker_table tr#master").click(function(){
  if($(this).css("background-color") == "#FFFFFF") { 
    $(this).css("background-color", "#C2DAEF");
  }
});

I think there is something wrong with my if statement. How do I check for a css value using jQuery?

+4  A: 

Looks like it gets returned in the form rgb(x, y, z), so your code should be:

$("#tracker_table tr#master").click(function(){
  if($(this).css("background-color") == "rgb(255, 255, 255)") { 
    $(this).css("background-color", "#C2DAEF");
  }
});

Edit: That being said, I'd suggest you use classes instead of inspecting/setting css properties directly. Something like this:

$("#tracker_table tr#master").click(function(){
  if(!$(this).hasClass("selected")) { 
    $(this).addClass("selected");
  }
});

Css:

tr { background-color: #FFFFFF; }
tr.selected { background-color: #C2DAEF; }
Alconja
That still doesn't work. There is something wrong with my if statement, because I tried adding an alert within the if statement and it never alerted, so I know the if statement isnt working correctly.
zeckdude
Alconja
+2  A: 

While this may work, in effect you are storing information in the form of colors, and then retrieving and comparing this information later. Alconja suggests an approach that will work, but ultimately you may be better off working with classes, whose names can be defined by you to carry appropriate meaning. It's much friendlier and less brittle to have something like this:

$('#tracker_table tr#master').click( function(){
    if ( $(this).hasClass('something') ) {
        $(this).removeClass('something').addClass('something_else');
    }
})
Ken Redler
This is probably the way to go, I assume the colors have some sort of meaning like "selected row" or whatnot.
R0MANARMY
What if your project stakeholders decide that whatever white means now, they'd prefer it be light gray? No, not that gray, another gray. And make that blue a little greener, too. Using semantic classnames means an easy change in your style sheet, and your code continues to mean what it says. If it's just 'selected', then yes, that's pretty easy. tr class="selected", versus no class.
Ken Redler