Gabriel Uhlíř
Gabriel Uhlíř

Reputation: 639

How to change color based on element contents?

I want to color div.rating. But with values 0.0, 1.0 or 2.0 etc the div background is always white. Where is the mistake please?

Here is my code:

var rating = $(".rating").text();
if("0.0" < rating && rating < "1.6")
{
  $(".rating").css({background: "red", color: "rgb(140,60,60)"});
}
else if("1.7" < rating && rating < "2.4")
{
  $(".rating").css({background: "yellow", color: "rgb(140,140,60)"});
}
else if("2.5" > rating && rating > "5.0")
{
  $(".rating").css({background: "green", color: "rgb(60,140,60)"});
}
else
{
  $(".rating").css({background: "white", color: "rgb(60,60,60)"});
}

Upvotes: 1

Views: 112

Answers (3)

Saeed Neamati
Saeed Neamati

Reputation: 35812

In JavaScript both these conditions result to true:

  "0.0" < "5"; // true;
  "10" < "5"; // true;

You have to first convert the rating value to a number. Try this:

 var rating = Number($('.rating').text()); // Converting the string into number
 if(Boolean(rating)) // If the text was a valid number
 {
     if ( 0 < rating && rating < 0)
     {
          // Now do what you want to do here.
     }
 }

Upvotes: 1

Iain
Iain

Reputation: 2309

It's background-color if you are just wanting to set the colour. Not background.

Upvotes: 0

rajasaur
rajasaur

Reputation: 5450

rating is a String, you need to convert that to float. With your current code, it never matches and you get the default case which is white

var rating = parseFloat($(".rating").text());

Upvotes: 3

Related Questions