0

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?

2
  • Why do you repeat {'background-color':} in the inner ternary expression? Don’t do that. Commented Jul 4, 2016 at 11:46
  • 1
    The right term is ternary operator. Unlike if-else statements the ternary operator is an expression, which can be used inside function argument lists or object/array literals. Commented Jul 4, 2016 at 11:56

2 Answers 2

3

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)})
Sign up to request clarification or add additional context in comments.

1 Comment

inline please :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.