Forum Moderators: open

Message Too Old, No Replies

mixed string & variable in conditional statement

         

sssweb

1:32 am on Mar 9, 2006 (gmt 0)

10+ Year Member



Can you mix a string with a variable in a?: conditional statement? I'm trying to print out some HTML and can't get the formatting right.

var code = (x=5)?"width=\""x:"width=\""(x-1);

For x=5, I want to print: width="5"
Else print: width="4"

Rambo Tribble

2:26 am on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<script type="text/javascript">
var x=4
alert(x==5? "width = "+x : "width = "+(x-1));
</script>

Bernard Marx

9:27 am on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Don't forget the quotes, Rambo.

var code = 'width="'+ (x==5? x:x-1) + '"'; 

But that doesn't quite match this...

For x=5, I want to print: width="5"
Else print: width="4"

This does:

var code = 'width="'+ (x==5? 5:4) + '"'; 

Rambo Tribble

2:10 pm on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Actually, from the written description I wonder if simply:

var code = "width = "+ (x==5? x : 4);

isn't closer to what is desired. I'm not sure but what the extra quotes were attempting number/string conversion, unnecessarily.

sssweb

2:17 pm on Mar 9, 2006 (gmt 0)

10+ Year Member



Thanks to all; I can make it work from here.

Bernard Marx

3:17 pm on Mar 9, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The extra quotes were to produce: width="n"