views:

267

answers:

8

I'm trying to improve my jquery/javascript syntax. Is there a better way to write this?

if (ok)
 var mymsg  = '<p id="ok-box">'
      +   "You're good to go"
    + '</p>';
}else {
 var mymsg  = '<p id="not-ok-box">'
      +   "Error"
    + '</p>';
}

I was thinking if jquery/javascript had a similar syntax to the following PHP syntax, it would be great:

$mymsg = ($ok) ? "You're good to go" : "Error";
+2  A: 

The best way to write that in my view is:

if (ok)
  var mymsg = '<p id="ok-box">You\'re good to go</p>';
} else {
  var mymsg = '<p id="not-ok-box">Error</p>';
}

Ternary operators make the code more confusing, not less. The most obvious change I can see is to get rid of superfluous string appending, and do it all in one go. The strings you've got are very straightforward, and don't really need to be broken up into 3 lines each.

Dominic Rodger
Why the downvote? Have I done something wrong?
Dominic Rodger
It wasn't me that down-voted, but I think it's because instead of answering the question, you tried to convince us why what's being asked is not worth it and that your way is better - which kind of doesn't answer the question ;) but it wasn't me who down-voted
Chris
+1 since this is so much better than the versions with multiple ternary operators.
daveb
@Chris - your question begins "I'm trying to improve my jquery/javascript syntax. Is there a better way to write this?". My answer begins "The best way to write that...".
Dominic Rodger
+11  A: 

You mean like:

var mymsg = ok ? '<p id="ok-box">You\'re good to go</p>' :
    '<p id="not-ok-box">Error</p>';

It does! :)

Anthony Mills
Hurrah for using the ternary operator just once.
daveb
Yeah, I think the ternary operator is great for saving space, and sometimes the clearest code is the smallest code.
Anthony Mills
A: 
Peter Payne
-1 for not understanding JavaScript Scoping.
Tim Büthe
Don't use `PRE` for code, just indent by 4 spaces.
random
I fixed it already, but my fix got trounced. I've now rolled back.
Dominic Rodger
A: 

You can use a ternary statement (that's the fancy name for the if on one line trick):

var is_ok = true;
var myMsg = is_ok ? "You're good to go" : "Error";

But you are changing two parts of your p tag so you might want to do something like this instead:

// defaults
var myMsg = "You're good to go";
var msgClass = "ok-box";

if ( !is_ok ) {
  myMsg = "Error";
  msgClass = "not-ok-box";
}

Trouble with that is you now have two variable flying around...not very tidy so instead you can wrap them up 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 neater and all self contained.

var myBox = '<p class="' + msgClass + '">' + myMsg + '</p>';

However I'd create the element using code (which I don't know how to do in jquery as I'm a mootools boy). In mootools it would be something like this:

myBox = new Element( "p", { class : msgClass, html : myMsg } );
Pete Duncanson
essentially, a custom hand rolled template engine =) might as well use a template library and save some code.
Chii
Yep, hence the mootools version at the end, full circle. Better to use the DOM (and even then a library version of the DOM code to make it cross browser and easier to work with). Original question answered at the top, some leading of the nose in the middle to a better way of doing stuff at the end ;)
Pete Duncanson
A: 

Do you looking for the mmost understandable? Or shortest? Does the element really need different ids?

var mymsg = '<p id="' + (ok ? '' : 'not-') + 'ok-box">' + (ok ? "You're good to go" : 'Error') + '</p>';
Tim Büthe
The id is for styling
Chris
A: 

If you have to use ternary operators in your code (try not to, it makes it terribly hard to follow later on), try surrounding them with brackets to look more like if statements to make them easier to follow:

var mymsg = '<p id="' + (!ok ? 'not-' : '') + 'ok-box">' + (ok ? 'You\'re good to go' : 'Error') + '</p>';
Nathan Kleyn
+1  A: 

Think javascript templates - they are much better than hard coding strings, and mixing logic with presentation code. google saw a viable one (no doubt more out there): http://peter.michaux.ca/articles/javascript-template-libraries

<script language="javascript">
    //call your methods and produce this data
    var data = ok?{cssClass:"ok-box",msg:"OK some custom msg"}
                 :{cssClass:"not-ok-box",msg:"NOT OK custom msg"};
</script>
<textarea id="msg_template" style="display:none;">
  <p id="${cssClass}">${msg}</p>
</textarea>
<script language="javascript">
    var result = TrimPath.processDOMTemplate("msg_template", data);
    document.getElementById('content').innerHTML = result;
</script>
Chii
trimpath! i thought that lib has been dead for 3 years.
mkoryak
heh, may be, but there are plenty of other js templating libraries, and they are all pretty much equally good. I just chose this because it was the first result of google =)
Chii
A: 

I would expand on a few of the answers above. You can utilize jquery much more here. Even though it doesn't really add much except convenience.

var myMsg = "You're good to go";
var msgClass = "ok-box";

if ( !ok ) {
  myMsg = "Error";
  msgClass = "not-ok-box";
}

If this is within a function then don't worry about namespacing the variables. They'll be local anyway. Than since you're using jquery, use it to create the elements.

var okbox = $('<p id="' + msgId + '">' + myMsg + '</p>').get();

You can then append okbox anywhere using jquery methods.

$('#content').append(okbox);

Since it's a small snippet of html code you shouldn't have to worry about performance. Of course YMMV.

Marco