4

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

9 Answers 9

12

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! :)

Sign up to request clarification or add additional context in comments.

2 Comments

Hurrah for using the ternary operator just once.
Yeah, I think the ternary operator is great for saving space, and sometimes the clearest code is the smallest code.
1

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.

3 Comments

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
+1 since this is so much better than the versions with multiple ternary operators.
@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...".
1

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>

2 Comments

trimpath! i thought that lib has been dead for 3 years.
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 =)
0

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>';

Comments

0

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>';

Comments

0

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

2 Comments

essentially, a custom hand rolled template engine =) might as well use a template library and save some code.
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 ;)
0

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.

Comments

0

Here you go

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

Comments

-1

Don't declare your variables in a scope that will disappear before you use the variable.

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

BTW idiots who promote dangerous scoping without understanding how badly that will bite you in other languages should be hung.

1 Comment

I fixed it already, but my fix got trounced. I've now rolled back.

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.