vkoukou
vkoukou

Reputation: 142

Comparing negative values does not work properly in Javascript

I have the following code which changes the background color of a table data cell according to the numerical value inside the cell.
While all other comparisons work as expected, (val<(-3000)) comparison never enters the block.
This is the code:

//Change Background Color for all P/L values
$(".PLcolors").each(function(index, value) {

  var val = Number(parseFloat($(this).text(), 10));

  console.log("value is " + val);

  if (val === 0) {
    $(this).css("background-color", "#DCDCDC");
  } else if ((val => -3000) && (val <= 3000)) {
    $(this).css("background-color", "#F0E68C");
  } else if (val < (-3000)) {
    $(this).css("background-color", "#FF0000");
  } else if ((val > 3000)) {
    $(this).css("background-color", "#008000");
  }
});

the type of val variable is number.

Upvotes: 1

Views: 1577

Answers (1)

Erazihel
Erazihel

Reputation: 7605

There is an error inside your JS, you set => instead of >=. Fix it to:

else if (val >= -3000 && val <= 3000) {

//Change Background Color for all P/L values
$(".PLcolors").each(function(index, value) {

  var val = Number(parseFloat($(this).text(), 10));

  console.log("value is " + val);

  if (val === 0) {
    $(this).css("background-color", "#DCDCDC");
  } else if (val >= -3000 && val <= 3000) {
    $(this).css("background-color", "#F0E68C");
  } else if (val < -3000) {
    $(this).css("background-color", "#FF0000");
  } else if ((val > 3000)) {
    $(this).css("background-color", "#008000");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="PLcolors">1</li>
  <li class="PLcolors">-3001</li>
  <li class="PLcolors">3001</li>
  <li class="PLcolors">0</li>
</ul>

Upvotes: 2

Related Questions