3

Just getting to grips with javascript and jquery

I am setting backgroundColor of a table cell based on its value.

 $("td.ms-vb2").filter(function(index){return $(this).text() === "Yes";}).css("backgroundColor", "#81F79F");
 $("td.ms-vb2").filter(function(index){return $(this).text() === "No";}).css("backgroundColor", "#FE642E");

Could someone tell me how I would be able write an if-else statement where if the color is #81F79F do an alert and if the color is #FE642E, do another alert

OR

if the value in the cell is Yes do an alert and if the value in the cell is No, do another alert

Many thanks

BenG
  • 14,826
  • 5
  • 45
  • 60
SharePointDummy
  • 347
  • 1
  • 6
  • 22

3 Answers3

1

Grab the color from the element, then check it as you wish. Since jQuery seems to return background-color as an rgb color, you would either have to convert it to hex, or check against the equivalent rgb.

Check out this question if you want a function to convert the color value.

var color = $('td.ms-vb2').css('background-color');
if (color == 'rgb(129,247,159)')
    alert('#81F79F');
else if (color == 'rgb(254,100,46)')
    alert('#FE642E');

Alternatively, you could do a similar bit of code to check the text (this is probably the easier solution in this case)

var value = $('td.ms-vb2').text();
alert(value == "Yes" ? "Yes!" : "No...");
Community
  • 1
  • 1
Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55
1

your best bet is to probably add a class to the td if it is yes, or a different class if it is no. and then test basis existence of the class.

for example add the class affirmative or negative

then in your css have a style for affirmative or negative and declare the background-color there. that way, all your js needs to do is change the class

James Holland
  • 118
  • 1
  • 7
0

You can use each() function to do all what you need:

Set cell background-color:

$('td.ms-vb2').each(function(){
    var cell = $(this)
    if (cell.text() == "Yes")
        cell.css('background-color', '#81F79F');
    else if (cell.text() == "No")
        cell.css('background-color', '#FE642E');        
});

Show alerts:

$('td.ms-vb2').each(function(){
    var color = $(this).css('background-color');
    if (color == '#81F79F')
        alert('#81F79F');
    else alert('another color');
});
Ragnar
  • 4,393
  • 1
  • 27
  • 40