Conditional Logic For Decision Making: jQuery

In this video tutorial we shall see how to make our applications smarter with artificial intelligence using conditional logic for decision making, using jQuery.

Here we take 2 numbers from the user and using jQuery, we find the result of division of those two numbers. If the user tries to divide by zero, then we alert the user with a message, that “Division by zero is not allowed”. Thus making our application smarter and get the feel of artificial intelligence!

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head><title>Conditional Logic For Decision Making: jQuery</title></head>
<body>
 
<form>
No1: <input type="text" id="no1" /><br />
No2: <input type="text" id="no2" />
<button>Division</button>
</form>
 
<span></span>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have a form, with 2 input box and a button.
There is a span tag to display the appropriate messages.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready( function() {
 
 $("button").click( function() {
     var no1 = $("#no1").val();
 var no2 = $("#no2").val();
 
 if( no2 == 0 )
   $("span").html("Division by zero not allowed!");
 else if( no2 == 1 )
   $("span").html("Division of "+no1+" and "+no2+" is "+(no1/no2));
 else
 
 $("form").submit( function() { return false; });
 });
});

Here we fetch and assign the values entered by the user to local variables.
using conditional operator, if else, we see if the second number entered by the user is zero.
If its zero, we show “Division by zero not allowed!” message, else we show the result of division.

We also need to make the form submit return false, so that the form doesn’t try to redirect to some other page once the user clicks on the submit button.

Video Tutorial: Conditional Logic For Decision Making: jQuery


[youtube https://www.youtube.com/watch?v=JMXbyAUMmEk]

YouTube Link: https://www.youtube.com/watch?v=JMXbyAUMmEk [Watch the Video In Full Screen.]



Comparison Operators
1. Equality: a == b;
2. Inequality: a != b;
3. Exactly Equal: a === b;
4. Greater than: a > b;
5. Greater than or equal to: a >= b;
6. Less than: a < b; 7. Less than or equal to: a < = b; Logical Operators: Negation: !a OR: a || b; AND: a && b;

TruthTable

Negation: True if a is false or doesn’t exist in the DOM.
OR: True if a is true or b is true, or if both are true, but not if both are false.
AND: True if a is true and b is true, but not if one or the other is false.

Ternary Operator
Ex: a > b ? if_true_code : else_this_code;

If a is greater than b, then if_true_code will be executed, else else_this_code will be executed.

Also see Ternary Operator in C for understanding the logic.
Biggest of Two Numbers Using Ternary Operator: C++.
Biggest of 3 Numbers Using Ternary Operator: C++.

Note: If there is only 1 statement inside the if and/or elseif and/or else, we need not put the code inside the brackets. If there are multiple statements then we MUST put the code inside the brackets. Also we can have any number of elseif’s in a if else block, but only 1 if and only 1 else part in it. We could have any number of if-elseif-else blocks in a program.

Also note that, we can have if without elseif and else. But we can not have elseif and else without if!

Dynamically Load Images: jQuery Looping

Video tutorial to demonstrate loading of images dynamically using jQuery looping method: .each()

In this tutorial, we take 5 div elements in our html document, and then using each() method, we loop through each of these div tags and insert images in each one of them.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<html>
<head><title>Dynamically load images: jQuery Looping</title>
<style type="text/css">
div  {
 
display: inline;
padding: 10px;
 
}
 
</style>
 
</head>
<body>
 
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
 
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have 5 div tags, and we have applied some cascading stylesheet property to it.

jQuery code
my_script.js

1
2
3
4
5
6
7
$(document).ready( function() {
 
 $("div").each( function(i) {
  $(this).append("<img src='images/"+(++i)+".png' width='79' height='79' />");
 });
 
});

Here we select all the div tags and loop through each one of them using each() method.
Using this selector, we append image tag with a image to each div present in our html document.

+ is concatenation operator.
i++ is a shorthand notation of i = i + 1;

++i is pre increment.
i++ is post increment.

Similarly,
– -i is pre decrement.
i- – is post decrement.

Ex:

let i = 1;

display or echo ++1; results in 2. after display i = 2;
display or echo i++; results in 1. after display i = 2;

folder-structure-jquery

Note: We have our images inside a folder called images.

Video Tutorial: Dynamically Load Images: jQuery Looping


[youtube https://www.youtube.com/watch?v=r-7ljuuljgY]

YouTube Link: https://www.youtube.com/watch?v=r-7ljuuljgY [Watch the Video In Full Screen.]



each() method is often used in all the application level programming logic.
We would also use a static method $.each() when we encounter ajax in jQuery. We would explain it in further videos. Stay subscribed to our blog and youtube channel and please like and share our tutorials with your friends.

jQuery Filter Methods To Narrow Selection

In this video tutorial we illustrate the use of jQuery filter methods to narrow our selection.

The 6 jQuery filter methods are:
first()
last()
eq()
slice()
not()
filter()

In this example, we take some list of images and using CSS we make the display property to none. Hence hiding all the images from being displayed.
Using filter methods we write our jQuery script to fetch elements(images).

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<html>
 <head><title>Filter Methods to narrow the selection!</title>
 
  <style type="text/css">
   li {
    display: none;
   }
  </style>
 
 </head>
 <body>
    <ol>
      <li>
         0<img src="images/aperture.png" width="79" height="79" />
      </li>
      <li>
         1<img src="images/coda.png" width="79" height="79" />
       </li>
      <li class="no">
         2<img src="images/finder.png" width="79" height="79" />
      </li>
      <li>
         3<img src="images/photoshop.png" width="79" height="79" />
      </li>
      <li class="no">
         4<img src="images/safari.png" width="79" height="79" />
      </li>
    </ol>
 
    <button>Display!</button>                
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we have 1 button and 5 images. Images being numbered from 0 to 4.
Two of the list items have a class name of no.

jQuery code: first()
my_script.js

1
2
3
4
5
6
7
$(document).ready( function() {
 
  $("button").click( function() {
    $("ol").children().first().css( 'display', 'inline' );
  });
 
});

Here we are using chain methods and DOM Tree Traversal.
Also CSS method of jQuery. Also watch jQuery Methods and CSS: Restaurant Application

Here, we select ol tag and fetch all its children, and inturn select its first child, to which we apply the css property of display to inline.

Similarly,

jQuery code: last()
my_script.js

1
2
3
4
5
6
7
$(document).ready( function() {
 
  $("button").click( function() {
    $("ol").children().last().css( 'display', 'inline' );
  });
 
});

Here, we select ol tag and fetch all its children, and inturn select its last child, to which we apply the css property of display to inline.

jQuery code: eq()
my_script.js

1
2
3
4
5
6
7
$(document).ready( function() {
 
  $("button").click( function() {
    $("ol").children().eq(4).css( 'display', 'inline' );
  });
 
});

Here, we select ol tag and fetch all its children, and inturn select its 4th child using its index number, to which we apply the css property of display to inline.

jQuery code: slice()
my_script.js

1
2
3
4
5
6
7
$(document).ready( function() {
 
  $("button").click( function() {
    $("ol").children().slice(1, 4).css( 'display', 'inline' );
  });
 
});

Here, we select ol tag and fetch all its children, and inturn select its children from index 1 to 4 i.e., image 1, 2 and 3, to which we apply the css property of display to inline.

jQuery code: not()
my_script.js

1
2
3
4
5
6
7
$(document).ready( function() {
 
  $("button").click( function() {
    $("ol").children().not(".no").css( 'display', 'inline' );
  });
 
});

Here, we select ol tag and fetch all its children, and inturn select its children which do not have the class name no i.e., image 0, 1 and 3, to which we apply the css property of display to inline.

jQuery code: filter()
my_script.js

1
2
3
4
5
6
7
$(document).ready( function() {
 
  $("button").click( function() {
    $("ol").children().filter(".no").css( 'display', 'inline' );
  });
 
});

This is opposite of not() method.
Here, we select ol tag and fetch all its children, and inturn select its children which has the class name no i.e., image 2 and 4, to which we apply the css property of display to inline.

Video Tutorial: jQuery Filter Methods To Narrow Selection


[youtube https://www.youtube.com/watch?v=DGoCpgi1LK4]

YouTube Link: https://www.youtube.com/watch?v=DGoCpgi1LK4 [Watch the Video In Full Screen.]



These are the 6 filter methods of jQuery, using which we can narrow down our selection.

I’m using images to make sure the learning stays colorful and not pale boring text. These filter methods will come in handy in later stages wherein we under take some complex application developments. These type of methods save us time and the number of line of code, to achieve the same thing manually.

DOM Tree Traversal: jQuery

In this video tutorial presentation we will explain the DOM Tree Traversal using jQuery methods.

The jQuery methods we are using are
parent()
children()
prev()
next()
siblings()
and some examples to show the use of Chain methods.

HTML code
index.html

1
2
3
4
5
6
7
8
 <div id="main">
  <img src="logo.png" />
  <ol>
   <li>Apple</li>
   <li>Oracle</li>
   <li>Microsoft</li>
  </ol> 
</div>
1
 $("ol").parent();

is div with an id main.

1
 $("ol").children();

is, all li. i.e., Apple, Oracle, Microsoft will be displayed.

1
 $("img").parent();

is div with an id main.

1
 $("li").parent().parent();

parent of li is ol and its parent is div tag with an id main.
This is also called as chain method.

Video Tutorial: DOM Tree Traversal: jQuery


[youtube https://www.youtube.com/watch?v=bBtkD6t0_tU]

YouTube Link: https://www.youtube.com/watch?v=bBtkD6t0_tU [Watch the Video In Full Screen.]



How to test these methods:
Looking at our previous day tutorials, write a simple program with some html element structures and take a button.
Clicking on the button, you call each of these methods and see the output.

Keep the programs simple, so that you can first understand the output. Later these simple DOM tree traversal techniques will be very useful while you encounter with some complex application development.

jQuery Methods and CSS: Restaurant Application

Video tutorial illustrates the use of jQuery methods to add and remove CSS class to HTML elements on the fly or dynamically.

Let’s assume that we have a client and her requirements:
She has a menu with both vegetarian and non-vegetarian items in it.
Once her customer clicks on a button called Vegetarian, all the vegetarian items must get highlighted in the menu.
Once the customer clicks on Restore button, all the highlighting must disappear and the menu must look as before.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
 <head><title>jQuery Methods and CSS!</title>
  <style type="text/css">
   .highlight{
     background-color: lightgreen;
     width: 100px;
   }
  </style>
 </head>
 <body>
         <ol>
          <li class="veg">Rice</li>
          <li class="non_veg">Chicken</li>
          <li class="veg">Veg Pizza</li>
          <li class="non_veg">Fish</li>
          <li class="veg">Fruits and Juice!</li>
         </ol>
         <br />
 
         <button id="select_veg">Vegitarian</button>
         <button id="restore_menu">Restore</button>
 
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we have an ordered list with some list items in it.
The vegetarian items have a class name of veg.
and non-vegetarian items have a class name of non_veg.

Two buttons with its respective ID’s.

Some CSS coding:
It has 1 class which has a background color of light green and a width of 100px.

This class must be dynamically applied to the list items with class name veg, upon clicking of the button Vegetarian.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
 $("#select_veg").click( function() {
    $("li.veg").addClass("highlight");
 });
 
 $("#restore_menu").click( function() {
    $("li.veg").removeClass("highlight");
 });
 
});

Once the document is loaded and ready we call an anonymous function.
When the user clicks on the button with an id of select_veg, we select all the list items with the class veg and add the CSS class highlight to it, using addClass method of jQuery. Which brings light green background color to those list items.

When the user clicks on Restore button which has an id of restore_menu, we remove the CSS class highlight from all the list items using removeClass method of jQuery.

Video Tutorial: jQuery Methods and CSS: Restaurant Application


[youtube https://www.youtube.com/watch?v=1Y_aBjqGgO4]

YouTube Link: https://www.youtube.com/watch?v=1Y_aBjqGgO4 [Watch the Video In Full Screen.]



This creates a great user experience while viewing the items without reloading the menu page.

You could use these methods addClass() and removeClass() to create such rich user experience in your applications.