views:

581

answers:

6

I have the following code in Javascript and Jquery:

     $("<li />")

     .html('Somehtml')

I would like to be able to change the content of .html by using if-else statement. My code should be something like this, however it's not working.

  var showinfo = <?php echo '$action'; ?>


     $("<li />")

    if (showinfo == 'action1'){
     .html('Somehtml')     
    else {
      .html('Other html')
      }

Any ideas how should I change it?

+1  A: 
var listItem = $("#yourLi");

if (showinfo == 'action1'){
 listItem.html('Somehtml')     
else {
  listItem.html('Other html')
  }
XGreen
+2  A: 

Don't interrupt the jquery chaining:

var showinfo = '<?php echo $action; ?>'

if (showinfo == 'action1'){
    $("<li />").html('Somehtml')     
} else {
    $("<li />").html('Other html')
}

Note: I also corrected an error in your php echo statement and a missing bracket in your if...else

adam
+5  A: 

Ternary operator?

$("<li />").html((showinfo == 'action1') ? 'Somehtml' : 'Other html');

The important thing to understand is that your first bit of code is being interpreted as one statement, not two:

 $("<li />")
 .html('Somehtml')

 //Is the same as:
 $("<li />").html('Somehtml');

You're getting mixed up because you're not using semicolons to terminate your statements. JavaScript allows this to support legacy code, but if you're writing code now you really should be using them.

Tobias Cohen
+1 for being more elegant and explaining the answer better than me!
adam
+1  A: 

You can shorten it as follows:

var showinfo = '<?php echo '$action'; ?>'


$("<li />")
.html( (showinfo == 'action1' ? 'Somehtml' : 'Other html') );

.html can be on the same line or a separate line as the statement is terminated with a semicolon. If you have multiple methods on a single selector I find separating them on multiple lines more readable.

ChrisP
Oooh I like this one too! Someone else not afraid of the ternary operator.
thomasrutter
If you don't need showinfo again, you can do:$("<li />").html( ('<?php echo '$action'; ?>'== 'action1' ? 'Somehtml' : 'Other html') );
dave1010
A: 

Adam's answer is pretty spot-on. To save a little bit of unnecessary duplication however you could modify it slightly to this:

var
    showinfo = '<?php echo $action; ?>',
    listitems = $("<li />");

if (showinfo == 'action1') {
    listitems.html('Somehtml');     
} else {
    listitems.html('Other html');
}
thomasrutter
Actually, ignore the above - I've just spotted ChrisP's answer which I like more - http://stackoverflow.com/questions/2489189/if-else-statement-within-jquery-function/2489510#2489510
thomasrutter
A: 

what if we wanted an if, elseif, elseif etc...?

Ben