1

I'm having trouble doing something that seems like it should be very simple. I want to simply set the text colour to red if the value is less than zero.

So in this first function I get the value, and upon "success" I want to set the colour to red if the balance < 0. Simple.

function getTimeBankBalance(staffid){

  if(staffid == undefined){
    var staffid = $('#staffid').val();
  }

  $.ajax({
    url: 'get-timebankbalance.php',
    type: 'GET',
    data: {
      cache: false,
      staffid: staffid
    },
    success: function(balance) {
      $('.timebankbalance').html(roundToTwo(balance) + " Hours");
      if(balance < 0) $('.timebankbalance.').css('color','red');
    },
    error: function(){
      genericPrompt("Error","Unable to calculate staff time bank balance","errormessage-inline");
    },
  });
}

The reason I'm using a class selector is because I have two places where the balance is displayed.

Anyway the above function is called when the page has finished loading.

$(function(){
  getTimeBankBalance();
});

But it doesn't seem to work. So I thought maybe it was a timing issue, and it appears to be because when I pause the code execution in the debugger the text turns red. Without the debugger it stays black.

So then I tried moving the code into a separate function

function setBalanceColour(balance){
  if(balance < 0){
    $('.timebankbalance.').css('color','red');
  }
}

And delaying that function call by a few seconds...

 setTimeout(setBalanceColour(balance),5000);

That didn't help either. So what's going on here? Why won't it change the colour?

Vincent
  • 1,741
  • 23
  • 35

1 Answers1

2

Like we discussed in the comments there is an extra period . in $('.timebankbalance.')

So this line:

if(balance < 0) $('.timebankbalance.').css('color','red');

would look like:

if(balance < 0) $('.timebankbalance').css('color','red');
crazymatt
  • 3,266
  • 1
  • 25
  • 41
  • Are you not missing curly braces? – Sleek Geek Apr 12 '19 at 01:51
  • @SleekGeek the code in my answer is a copy of OP code with the period removed. But in JS you can do one line `if` statments. [You can read about that here](https://stackoverflow.com/questions/4797286/are-braces-necessary-in-one-line-statements-in-javascript). – crazymatt Apr 12 '19 at 15:31