jQuery if else

jQuery does not have a separate if else statement.. it uses the JavaScript if else statement.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else if to specify a new condition to test, if the first condition is false
  • Use else to specify a block of code to be executed, if the same condition is false

 

if statement

 

Syntax


if (condition) {
   // code to be executed if the condition is true
} 

Here is an example of if statement in jQuery:
 

HTML

<p id="display"></p>

jQuery

var a = 10;

if(a > 0){
$("#display").text(a + " is greater than 0");
}

 

Output

 
The output will be : 10 is greater than 0
 

 

if else statement

 

Syntax:

 


if(condition){
    //code to execute if condition is true
}
else{
    //code to execute if condition is false
}

Here is an example of if else statement in jQuery:
 

jQuery

var a = -10;

if (a > 0) {
  $("#display").text(a + " is greater than 0");
} else {
  $("#display").text(a + " is greater than 0");
}


 

Output

 
The output will be : -10 is greater than 0
 

 

else if statement

 

Syntax:


if (condition1) {
    //code to be executed if condition1 is true
} else if (condition2) {
    //code to be executed if the condition1 is false and condition2 is true
 } else {
   //code to be executed if the condition1 is false and condition2 is false
}

Here is an example of else if statement in jQuery:
 

jQuery

var a = 0;

if (a > 0) {
  $("#display").text(a + " is greater than 0");
} else if (a < 0) {
  $("#display").text(a + " is greater than 0");
} else {
  $("#display").text("a is equal to 0");
}

 

Output

 
The output will be : a is equal to 0
 

 

© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags