I'm working on a web app that must display one or another value depending on the state of a boolean value. I need it to display "ON" if my var
"value" is true
, else it must display "OFF".
I did this code, and I was pretty sure it was going to work, but I was mistaken:
var value = true // actually this changes over time
var s = new String();
s += '<span style="color:white; font-size:14px; font-weight:bold;">'+ "ALRM H2S:" +'</span>';
s += '<span style="color: orange; font-size:14px; font-weight:bold;">'+ if(value){return "ON"} else {return "OFF"} +'</span>';
return s;
I get a "Syntax error at line (#3)". I think that the problem must be that I can't concatenate that if
else
statement, even if they return a string
, with the rest of the HTML elements.
What I'm doing wrong?.
You're right, you cannot have an if statement inline like that, so a ternary operator is what you should use in this case. You can use it like so:
var value = true; // actually this changes over time
var s = new String();
s += '<span style="color:white; font-size:14px; font-weight:bold;">' + "ALRM H2S:" + "</span>";
s += '<span style="color: orange; font-size:14px; font-weight:bold;">' + (value ? "ON" : "OFF") + "</span>";
return s;