Berecht Berecht - 5 months ago 21
CSS Question

inline if-else within inline if-else statement javascript

I am setting background colors to all cells in a table. Within the table there is only numeric data. The code below works. It sets the background of numbers bigger then 10 to green and lower or equal to 10 to red.

.css({'background-color':value >10 ? 'green' :'red'})


But when to want set three different colors as background I do not know how to put it in javascript properly. I want an ifelse statement within the ifelse statement. The code below should be close to the solution. It want to set the background of numbers bigger then 10 to green and lower then 5 to red. The numbers between 5 and 10 should be getting an orange background.

.css({'background-color':value >10 ? 'green' :'background-color':value <5 ? 'red' :'orange'})


What is wrong with the code?

Answer

Always use parenthesis if you have nested inline if:

.css({'background-color': (value > 10 ? 'green' : (value < 5 ? 'red' : 'orange'))})

You should refactor your code into another function to avoid if-else hell, and keep your code cleaner:

function valueToColor(value) {
  if(value > 10) return 'green';
  if(value >= 5) return 'orange';
  return 'red';
  // equivalent to: return (value > 10 ? 'green' : (value < 5 ? 'red' : 'orange'))
}

// ...

.css({'background-color': valueToColor(value)})