You can use the ternary operator (this is a fancy name for the if trick on the same line):
var is_ok = true; var myMsg = is_ok ? "You're good to go" : "Error";
But you are changing the two parts of your p tag, so instead you can do something like this:
// defaults var myMsg = "You're good to go"; var msgClass = "ok-box"; if ( !is_ok ) { myMsg = "Error"; msgClass = "not-ok-box"; }
The problem with this is that now you have two variables that fly ... not very neat, so you can wrap them in an object:
var myMsg = { text : "You're good to go", cssClass : "ok-box" } if ( !is_ok ) { myMsg.text = "Error"; myMsg.cssClass = "not-ok-box"; }
which is tidier and fully autonomous.
var myBox = '<p class="' + msgClass + '">' + myMsg + '</p>';
However, I would create the element using code (which I do not know how to do in jquery since I am a mootools boy). In mootools, it will be something like this:
myBox = new Element( "p", { class : msgClass, html : myMsg } );
source share