Berecht
Berecht

Reputation: 1145

Ternary Expression within Ternary Expression 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 a ternary expression within a ternary expression. The code below should be close to the solution. I 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?

Upvotes: 0

Views: 2308

Answers (2)

Wikiti
Wikiti

Reputation: 1636

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)})

Upvotes: 3

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

My suggestion is to pull out that code with a variable. It does not work because you are not grouping the ternary conditional statements and the repeated {background-color} key.

This works:

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

Try it:

function alertit(value) {
    var variable = (value >10 ? 'green' : (value <5 ? 'red' :'orange' ));
    alert(variable);
}

alertit(document.getElementsByTagName('input')[0].value)
Change value: <input type="text" value="3" onchange="alertit(this.value)">

Upvotes: 0

Related Questions