Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'If'-'else' statement within jQuery function

I have the following code in JavaScript and jQuery:

     $("<li />")

     .html('Some HTML')

I would like to be able to change the content of .html by using an 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('Some HTML')
else {
    .html('Other HTML')
}

How should I change it?

like image 676
Vonder Avatar asked Dec 30 '25 19:12

Vonder


1 Answers

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.

like image 183
Tobias Cohen Avatar answered Jan 01 '26 19:01

Tobias Cohen