tags:

views:

57

answers:

4
(category=="Villor/Radhus mm")?byId("nav_sub_villor").style.display='block' :  byId("nav_sub_villor").style.display='none';

I would like to call a function if the statement above is true...

But it doesn't seem possible...

Just want to be sure it is not possible, does anybody know?

+3  A: 

Sure you can:

function doIfTrue()
{
    byId("nav_sub_villor").style.display='block';
    // call other function
}

function doIfFalse()
{
    byId("nav_sub_villor").style.display='none';
}

(category=="Villor/Radhus mm") ? doIfTrue() : doIfFalse();

Note that an expression something like condition ? statement; statement : statement; is illegal in JS.

However if you really need to keep it a one-liner, you can push it all into an anonymous function:

(category=="Villor/Radhus mm") ? function() { byId("nav_sub_villor").style.display='block'; doOtherStuff();}() :  byId("nav_sub_villor").style.display='none';
Yuval A
A: 

You can have multiple statements or function calls in this ternary statement. To call another function if true, just add it before or after the first section where you set the display to 'block'.

atxryan
false, you cannot. `condition ? statement; statement : statement;` is illegal syntax in JS
Yuval A
You are correct. I should have tested this in JavaScript. The semicolon after first statement is ending the operator here.
atxryan
Technically, you can include multiple *expressions* (not statements) if you separate them with the `,` operator, but you need to put them in parentheses. I would definitely stay away from that though, since it would get really ugly.
Matthew Crumley
A: 

Why would you want to shorten an if statement in that way? You're just going to give headaches to the next person to come along and maintain it.

if (category=="Villor/Radhus mm")
    byId("nav_sub_villor").style.display='block';
else
    byId("nav_sub_villor").style.display='none';
Plutor
+1  A: 

It is possible. You can wrap your code inside an anonymous function and immediately call it. For instance, this one first alerts I'm in a function and then alerts 1

var i=1;
var a =  (i==1) ? (function(){alert("I'm in a function"); return 1})() : (function(){return 2})();
alert(a);

EDIT: Sorry, this is named self-invoking function, see here: http://www.hunlock.com/blogs/Functional_Javascript

naivists